使用递归或者非递归的方式实现二叉树的遍历,要求输入为二叉树各节点的值,输出为建立二叉树的深度
时间: 2024-02-26 07:56:31 浏览: 25
好的,这个问题我可以回答。首先,我们需要了解一下二叉树的遍历方式,包括先序遍历、中序遍历和后序遍历。其中,先序遍历的顺序是:先遍历根节点,然后遍历左子树,最后遍历右子树;中序遍历的顺序是:先遍历左子树,然后遍历根节点,最后遍历右子树;后序遍历的顺序是:先遍历左子树,然后遍历右子树,最后遍历根节点。
接下来,我将分别介绍递归和非递归实现这三种遍历方式的方法,并在实现过程中统计深度。
## 递归实现
先序遍历:
```python
def preorder(root, depth):
if root:
print(root.val)
depth += 1
depth = preorder(root.left, depth)
depth = preorder(root.right, depth)
return depth
```
中序遍历:
```python
def inorder(root, depth):
if root:
depth = inorder(root.left, depth)
print(root.val)
depth += 1
depth = inorder(root.right, depth)
return depth
```
后序遍历:
```python
def postorder(root, depth):
if root:
depth = postorder(root.left, depth)
depth = postorder(root.right, depth)
print(root.val)
depth += 1
return depth
```
## 非递归实现
先序遍历:
```python
def preorder(root):
stack = [root]
depth = 0
while stack:
node = stack.pop()
if node:
print(node.val)
depth += 1
stack.append(node.right)
stack.append(node.left)
return depth
```
中序遍历:
```python
def inorder(root):
stack = []
depth = 0
node = root
while node or stack:
while node:
stack.append(node)
node = node.left
node = stack.pop()
print(node.val)
depth += 1
node = node.right
return depth
```
后序遍历:
```python
def postorder(root):
stack = [root]
depth = 0
visited = set()
while stack:
node = stack[-1]
if node.left and node.left not in visited:
stack.append(node.left)
elif node.right and node.right not in visited:
stack.append(node.right)
else:
stack.pop()
visited.add(node)
print(node.val)
depth += 1
return depth
```
以上就是二叉树遍历的递归和非递归实现方法,同时也统计了建立二叉树的深度。希望能够对你有所帮助!