实现二叉树的前序遍历、中序遍历和后序遍历。
时间: 2023-12-15 16:32:52 浏览: 91
实现二叉树的先,中,后序遍历操作
以下是Python实现二叉树的前序遍历、中序遍历和后序遍历的代码示例:
1. 前序遍历
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.preorder(root, res)
return res
def preorder(self, root, res):
if not root:
return
res.append(root.val)
self.preorder(root.left, res)
self.preorder(root.right, res)
```
2. 中序遍历
```python
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.inorder(root, res)
return res
def inorder(self, root, res):
if not root:
return
self.inorder(root.left, res)
res.append(root.val)
self.inorder(root.right, res)
```
3. 后序遍历
```python
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
self.postorder(root, res)
return res
def postorder(self, root, res):
if not root:
return
self.postorder(root.left, res)
self.postorder(root.right, res)
res.append(root.val)
```
阅读全文