Open sisterAn opened 4 years ago
这道题和二叉树的层次遍历相似,只需要把 reverse()
去除就可以了
var levelOrder = function(root) {
if(!root) return []
let res = [],
queue = [root]
while(queue.length) {
let curr = [],
temp = []
while(queue.length) {
let node = queue.shift()
curr.push(node.val)
if(node.left) temp.push(node.left)
if(node.right) temp.push(node.right)
}
res.push(curr)
queue = temp
}
return res
};
var levelOrder = function(root) {
const res = []
var dep = function (node, depth){
if(!node) return
res[depth] = res[depth]||[]
res[depth].push(node.val)
dep(node.left, depth + 1)
dep(node.right, depth + 1)
}
dep(root, 0)
return res
};
var levelOrder = function(root) {
let res = [], queue = [];
if(!root) return res;
queue.push(root);
while(queue.length) {
let len = queue.length;
res.push([]);
for(let i = 0;i<len;i++) {
let node = queue.shift();
res[res.length - 1].push(node.val);
if(node.left) queue.push(node.left);
if(node.right) queue.push(node.right);
}
}
return res;
};
使用广度优先遍历 然后再对数据进行分层
var levelOrder = function(root) {
if(!root || root.val == null) return []
let queue = []
let res = []
queue.push(root)
while(queue.length){
let len = queue.length
let curr = []
for(var i =0;i<len;i++){
let node = queue.shift()
curr.push(node.val)
if(node.left)queue.push(node.left)
if(node.right)queue.push(node.right)
}
res.push(curr)
}
return res
};
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例: 二叉树:
[3,9,20,null,null,15,7]
,返回其层次遍历结果: