树的深度优先遍历代码
时间: 2023-07-24 19:06:16 浏览: 76
js代码-深度优先遍历
树的深度优先遍历有两种方式,分别是前序遍历、中序遍历和后序遍历。以下是三种遍历方式的代码实现:
前序遍历:
```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
```
中序遍历:
```python
def inorderTraversal(root: TreeNode) -> List[int]:
if not root:
return []
stack = []
res = []
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
```
后序遍历:
```python
def postorderTraversal(root: TreeNode) -> List[int]:
if not root:
return []
stack = [root]
res = []
while stack:
node = stack.pop()
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
res.append(node.val)
return res[::-1]
```
以上代码均为非递归实现,利用了栈来模拟递归过程。
阅读全文