二叉树先序中序后序遍历代码
时间: 2023-11-10 10:07:35 浏览: 113
以下是二叉树先序、中序、后序遍历的代码:
```python
# 先序遍历
def preorderTraversal(root):
if not root:
return []
res = []
stack = [root]
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):
if not root:
return []
res = []
stack = []
while stack or root:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
res.append(node.val)
root = node.right
return res
# 后序遍历
def postorderTraversal(root):
if not root:
return []
res = []
stack = [root]
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]
```
阅读全文