数据结构二叉树的遍历实现
时间: 2023-11-28 18:05:43 浏览: 90
二叉树的遍历有三种方式:前序遍历、中序遍历和后序遍历。其中,前序遍历是先访问根节点,再访问左子树和右子树;中序遍历是先访问左子树,再访问根节点和右子树;后序遍历是先访问左子树和右子树,再访问根节点。以下是二叉树遍历的实现方法:
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 = []
if not root:
return res
res.append(root.val)
res += self.preorderTraversal(root.left)
res += self.preorderTraversal(root.right)
return res
```
2.中序遍历
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
res += self.inorderTraversal(root.left)
res.append(root.val)
res += self.inorderTraversal(root.right)
return res
```
3.后序遍历
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def postorderTraversal(self, root: TreeNode) -> List[int]:
res = []
if not root:
return res
res += self.postorderTraversal(root.left)
res += self.postorderTraversal(root.right)
res.append(root.val)
return res
```
阅读全文