非递归遍历,一个先序遍历和中序遍历得后序遍历代码
时间: 2024-04-29 14:21:38 浏览: 93
以下是非递归实现的先序遍历、中序遍历和后序遍历的代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorderTraversal(root: TreeNode) -> List[int]:
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 inorderTraversal(root: TreeNode) -> List[int]:
if not root:
return []
stack = []
res = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
res.append(node.val)
node = node.right
return res
def postorderTraversal(root: TreeNode) -> List[int]:
if not root:
return []
stack1 = [root]
stack2 = []
res = []
while stack1:
node = stack1.pop()
stack2.append(node)
if node.left:
stack1.append(node.left)
if node.right:
stack1.append(node.right)
while stack2:
node = stack2.pop()
res.append(node.val)
return res
```
这里给出了三个函数分别用于先序遍历、中序遍历和后序遍历,每个函数都是非递归实现的。这些函数都接受一个二叉树的根节点作为输入,并返回对应的遍历结果。
阅读全文