close
The Wayback Machine - https://web.archive.org/web/20201015042725/https://github.com/sisterAn/JavaScript-Algorithms/issues/47
Skip to content
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

Open
sisterAn opened this issue May 21, 2020 · 1 comment
Open

leetcode102:二叉树的层序遍历 #47

sisterAn opened this issue May 21, 2020 · 1 comment

Comments

@sisterAn
Copy link
Owner

@sisterAn sisterAn commented May 21, 2020

给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。 

示例:
二叉树:[3,9,20,null,null,15,7] ,

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
@plane-hjh
Copy link

@plane-hjh plane-hjh commented May 21, 2020

这道题和二叉树的层次遍历相似,只需要把 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
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
2 participants
You can’t perform that action at this time.