用栈来实现层序遍历和用队列来实现层序遍历的代码
时间: 2024-12-24 10:29:25 浏览: 4
层序遍历通常用于树形结构,而栈和队列都可以作为其数据结构基础。这里分别给出用栈和队列实现二叉树层序遍历的Python代码示例:
**用栈实现层序遍历(宽度优先搜索,广度优先搜索):**
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def levelOrder(root):
if not root:
return []
result = []
stack = [root]
while stack:
level_nodes = []
for _ in range(len(stack)):
node = stack.pop()
level_nodes.append(node.val)
# 将当前节点的左右孩子入栈
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
result.append(level_nodes)
return result
```
阅读全文