题目
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
例如: 给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
来源:力扣(LeetCode)leetcode-cn.com/problems/bi…
解题思路
- 根据题目要求,需要逐层遍历二叉树,我们可以用一个队列来遍历
- 将当前层的节点入队列,再通过for循环取队列中节点的值,这里的for循环的次数决定了本层节点值的顺序,偶数行按顺序排列,奇数行按倒序排列,for循环的长度就是队列当前节点个数。循环的同时将节点出队列,如果节点有子节点则子节点入队列。
- 重复第2步
代码实现
var levelOrderBottom = function (root) {
if (!root) return []
const queue = [root]
const ans = []
while (queue.length) {
const arr = []
const len = queue.length
const arrLen = ans.length
for (let i = 0; i < len; i++) {
const node = queue.shift()
//偶数行按顺序排列,奇数行按倒序排列
if (arrLen % 2 === 0)
arr.push(node.val)
else
arr.unshift(node.val)
if (node.left) queue.push(node.left)
if (node.right) queue.push(node.right)
}
ans.push(arr)
}
return ans
};
如有错误欢迎指出,欢迎一起讨论!