二叉树的前序中序后序代码
时间: 2023-12-04 11:41:54 浏览: 79
以下是Python实现二叉树前序、中序、后序遍历的代码:
```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]:
res = []
def dfs(node):
if not node:
return
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return res
# 中序遍历
def inorderTraversal(root: TreeNode) -> List[int]:
res = []
def dfs(node):
if not node:
return
dfs(node.left)
res.append(node.val)
dfs(node.right)
dfs(root)
return res
# 后序遍历
def postorderTraversal(root: TreeNode) -> List[int]:
res = []
def dfs(node):
if not node:
return
dfs(node.left)
dfs(node.right)
res.append(node.val)
dfs(root)
return res
```
阅读全文