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. Binary Tree Level Order Traversal #157

Open
Tcdian opened this issue May 13, 2020 · 1 comment
Open

102. Binary Tree Level Order Traversal #157

Tcdian opened this issue May 13, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 13, 2020

102. Binary Tree Level Order Traversal

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

Example

Given binary tree [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]
@Tcdian
Copy link
Owner Author

Tcdian commented May 13, 2020

Solution

  • JavaScript Solution
/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var levelOrder = function(root) {
    if (root === null) {
        return [];
    }
    const result = [];
    const queue = [[0, root]];
    while(queue.length !== 0) {
        const [level, node] = queue.shift();
        result[level] = result[level] || [];
        result[level].push(node.val);
        if (node.left) {
            queue.push([level + 1, node.left]);
        }
        if (node.right) {
            queue.push([level + 1, node.right]);
        }
    }
    return result;
};

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