利用先序序列建立二叉树,并输出先序、中序和后序序列,,使用非递归
时间: 2023-12-08 11:01:44 浏览: 86
以下是利用先序序列建立二叉树,并输出先序、中序和后序序列的非递归实现代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder):
if not preorder:
return None
root = TreeNode(preorder[0])
stack = [root]
i = 1
while i < len(preorder):
node = TreeNode(preorder[i])
if node.val < stack[-1].val:
stack[-1].left = node
else:
while stack and node.val > stack[-1].val:
temp = stack.pop()
temp.right = node
stack.append(node)
i += 1
return root
def inorderTraversal(root):
if not root:
return []
stack = []
res = []
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res
def preorderTraversal(root):
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return res
def postorderTraversal(root):
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
res.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return res[::-1]
```
其中,`buildTree`函数用于根据先序序列建立二叉树,`inorderTraversal`、`preorderTraversal`和`postorderTraversal`函数分别用于输出中序、先序和后序序列。这里使用了栈来辅助实现非递归遍历。
阅读全文