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

✅102. 二叉树的层序遍历 #91

Open
Ray-56 opened this issue Aug 17, 2020 · 1 comment
Open

✅102. 二叉树的层序遍历 #91

Ray-56 opened this issue Aug 17, 2020 · 1 comment

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Aug 17, 2020

102. 二叉树的层序遍历

题目

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

示例

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

    3
   / \
  9  20
    /  \
   15   7

返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
@Ray-56
Copy link
Owner Author

Ray-56 commented Aug 17, 2020

/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    const queue = [];
    const ret = [];
    if (root) {
        queue.push(root);
    }
    while (queue.length) {
        const len = queue.length;
        const item = [];
        for (let i = 0; i < len; i++) {
            const cur = queue.shift();
            item.push(cur.val);
            if (cur.left) {
                queue.push(cur.left);
            }
            if (cur.right) {
                queue.push(cur.right);
            }
        }
        ret.push(item);
    }
    return ret;
};

@Ray-56 Ray-56 added the BFS label Aug 17, 2020
@Ray-56 Ray-56 changed the title 102. 二叉树的层序遍历 ✅102. 二叉树的层序遍历 Aug 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant