-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
二叉树This will not be worked onThis will not be worked on完成 ✅待复习普通第一次📜详解Something isn't workingSomething isn't working
Description
题目
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
示例
示例 1:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回锯齿形层序遍历如下:
[
[3],
[20,9],
[15,7]
]
解题
解题方法
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function(root) {
if(!root) return []
let queue = [root], result = []
while(queue.length > 0) {
const length = queue.length
result.push([])
for(let i = 0; i < length;i++) {
const resultLength = result.length
let node = queue.shift()
if(resultLength % 2 === 0) {
result[resultLength - 1].unshift(node.val)
} else {
result[resultLength - 1].push(node.val)
}
if(node.left) {
queue.push(node.left)
}
if(node.right) {
queue.push(node.right)
}
}
}
return result
};Metadata
Metadata
Assignees
Labels
二叉树This will not be worked onThis will not be worked on完成 ✅待复习普通第一次📜详解Something isn't workingSomething isn't working