非递归深度优先遍历树
时间: 2024-02-09 11:05:48 浏览: 73
非递归遍历树
以下是非递归深度优先遍历树的实现代码:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorderNonrecursion(root):
if not root:
return
stack = []
stack.append(root)
while stack:
node = stack.pop()
visit(node)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
def visit(node):
print(node.val)
# 创建一个示例树
# 1
# / \
# 2 3
# / \
# 4 5
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
preorderNonrecursion(root)
```
输出结果为:
```
1
2
4
5
3
```
阅读全文