写出非递归的方法实现对给定二叉树的先序和层序遍历算法,并给出一组数据
时间: 2023-06-16 11:06:13 浏览: 118
以下是非递归实现二叉树的先序和层序遍历的代码:
```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):
if not root:
return []
stack, res = [root], []
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
def levelOrder(root: TreeNode):
if not root:
return []
queue, res = [root], []
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
```
以下是一组测试数据:
```
1
/ \
2 3
/ \ \
4 5 6
```
先序遍历结果为:[1, 2, 4, 5, 3, 6]
层序遍历结果为:[[1], [2, 3], [4, 5, 6]]
阅读全文