写出非递归的方法实现对给定二叉树的先序和层序遍历算法,并给出一组数据
时间: 2023-06-16 13:06:05 浏览: 92
非递归的先序遍历算法:
```python
def preorderTraversal(root):
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 levelOrderTraversal(root):
if not root:
return []
queue = [root]
res = []
while queue:
level = []
for i in range(len(queue)):
node = queue.pop(0)
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level)
return res
```
数据示例:
```python
# 先构造一棵二叉树
# 1
# / \
# 2 3
# / \ \
# 4 5 6
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.right = TreeNode(6)
# 先序遍历输出:[1, 2, 4, 5, 3, 6]
print(preorderTraversal(root))
# 层序遍历输出:[[1], [2, 3], [4, 5, 6]]
print(levelOrderTraversal(root))
```
阅读全文