题目
【剑指offer】032.1从上往下打印二叉树
【剑指offer】032.2 输出二维数组
【剑指offer】032.3 z形层序遍历
解法
第一题
二叉树的层序遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder(self, root: TreeNode) -> List[int]:
if not root: return []
nodes = [root]
res = []
while nodes:
nums = len(nodes)
for i in range(nums):
res.append(nodes[0].val)
if nodes[0].left: nodes.append(nodes[0].left)
if nodes[0].right: nodes.append(nodes[0].right)
nodes.pop(0)
return res
第二题
第三题
用两个栈实现,这个比较巧妙
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
# 用两个栈 轮着放
if not root:
return []
stack1 = [root]
stack2 = []
res = []
while stack1 or stack2:
tmp = []
if stack1:
while stack1:
top = stack1.pop(-1)
if top.left: stack2.append(top.left)
if top.right: stack2.append(top.right)
tmp.append(top.val)
elif stack2:
while stack2:
top = stack2.pop(-1)
if top.right: stack1.append(top.right)
if top.left: stack1.append(top.left)
tmp.append(top.val)
res.append(tmp)
return res