给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如: 给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
解题思路
利用迭代方式,遍历每层节点,然后通过判断当前层,将值是往前插入还是往后插入。
- 设置一个栈,存入每层的节点和每层编号,设第一层为编号0,
stack = [[0, root]]; - 从栈中取出一个值,里面含有当前树节点和当前节点的层数;
- 判断返回数组ans的长度是否等于当前层数编号,若等于,则向ans添加一个数组;
- 判断当前层数的奇偶性,如果为奇数则向
ans[层数编号]后面添加当前节点的值,否则向前添加。
代码
var zigzagLevelOrder = function(root) {
// 迭代
if (!root) return []
let stack = [[0, root]], ans = []
while(stack.length) {
let [index, root] = stack.pop()
if (ans.length == index) ans.push([])
if (index % 2) {
ans[index].push(root.val)
} else {
ans[index].unshift(root.val)
}
root.left && stack.push([index+1, root.left])
root.right && stack.push([index+1, root.right])
}
return ans
};