建立递归和非递归遍历的二叉树的设计思路
时间: 2023-06-29 21:04:40 浏览: 91
二叉树的遍历分为三种:前序遍历、中序遍历和后序遍历。
对于递归遍历,我们可以使用递归函数来实现。对于每个节点,先输出该节点的值,然后递归遍历左子树和右子树,直到到达叶子节点。
具体实现:
前序遍历:
```python
def pre_order(node):
if node is not None:
print(node.val)
pre_order(node.left)
pre_order(node.right)
```
中序遍历:
```python
def in_order(node):
if node is not None:
in_order(node.left)
print(node.val)
in_order(node.right)
```
后序遍历:
```python
def post_order(node):
if node is not None:
post_order(node.left)
post_order(node.right)
print(node.val)
```
对于非递归遍历,我们可以使用栈来实现。对于每个节点,先将其入栈,然后循环弹出栈顶元素,并输出该节点的值。如果该节点有右子树,则将右子树入栈;如果该节点有左子树,则将左子树入栈。这样可以保证先遍历左子树,再遍历右子树。
具体实现:
前序遍历:
```python
def pre_order(node):
stack = [node]
while stack:
node = stack.pop()
if node is not None:
print(node.val)
stack.append(node.right)
stack.append(node.left)
```
中序遍历:
```python
def in_order(node):
stack = []
while stack or node:
if node is not None:
stack.append(node)
node = node.left
else:
node = stack.pop()
print(node.val)
node = node.right
```
后序遍历:
```python
def post_order(node):
stack = []
last_visited = None
while stack or node:
if node is not None:
stack.append(node)
node = node.left
else:
peek = stack[-1]
if peek.right is not None and last_visited != peek.right:
node = peek.right
else:
last_visited = stack.pop()
print(last_visited.val)
```
以上是二叉树递归和非递归遍历的设计思路和代码实现。
阅读全文