给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层次遍历如下:
[
[3],
[20,9],
[15,7]
]
看到本题目,首先想到的是使用队列或栈,然而简单使用这两个数据结构都不可以。
- 队列
- 根节点3入队列
- 访问3,3出队列,右子节点20入队列,左子节点9入队列 => [3]
- 访问20, 7入队列, 15入队列, 访问9 => [20, 9]
- 然后依次访问7, 15 => [7, 15]
- 这样会造成一直由右向左遍历, 不符合题目要求
- 栈
- 根节点3如栈
- 访问3, 3出栈,左子节点9入栈,右子节点20入栈 => [3]
- 访问20, 20出战,15入栈, 7入栈 => [20]
- 访问7 => [7]
- 这样就越遍历越深,也不满足题目要求
在网上看到一个递归的答案,采取的是dfs遍历(先序遍历),但在遍历时会传入一个depth参数, 当遍历到depth深度时,把响应节点的值加入到res[depth], 代码如下:
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
def search(childroot, depth):
if not childroot:
return
if len(res) == depth:
res.append([])
if depth % 2 == 0:
res[depth].append(childroot.val)
else:
res[depth].insert(0, childroot.val)
search(childroot.left, depth + 1)
search(childroot.right, depth + 1)
search(root, 0)
return res
下面再分享一个双栈的想法,感觉很巧妙:
- stack1存储当前层的节点
- stack2存储下一层的节点
- 轮流访问stack1和stack2, 但是实现时要注意左、右子节点入栈的顺序
class Solution:
def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
res = []
stack1 = []
stack2 = []
ind = 0
stack1.append(root)
while stack1 or stack2:
if stack1:
res.append([])
while stack1:
top = stack1.pop()
res[ind].append(top.val)
if top.left:
stack2.append(top.left)
if top.right:
stack2.append(top.right)
ind += 1
if stack2:
res.append([])
while stack2:
top = stack2.pop()
res[ind].append(top.val)
if top.right:
stack1.append(top.right)
if top.left:
stack1.append(top.left)
ind += 1
return res
由此,可以发现,
- 单栈实现先序遍历
- 双栈可以实现层次遍历
- 队列实现实现层次遍历