-
Notifications
You must be signed in to change notification settings - Fork 639
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
leetcode102:二叉树的层序遍历 #47
Comments
这道题和二叉树的层次遍历相似,只需要把 广度优先遍历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;
}; |
使用广度优先遍历 然后再对数据进行分层
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:
[3,9,20,null,null,15,7]
,返回其层次遍历结果:
The text was updated successfully, but these errors were encountered: