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

199. Binary Tree Right Side View #126

Open
Tcdian opened this issue Apr 22, 2020 · 1 comment
Open

199. Binary Tree Right Side View #126

Tcdian opened this issue Apr 22, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 22, 2020

199. Binary Tree Right Side View

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

Example

Input: [1,2,3,null,5,null,4]
Output: [1, 3, 4]
Explanation:

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 22, 2020

Solution ( BFS )

  • 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 rightSideView = function(root) {
    if (root === null) {
        return [];
    }

    const queue = [[root, 0]];
    const result = [];

    while (queue.length !== 0) {
        const [node, depth] = queue.shift();
        result[depth] = node.val;
        if (node.left) {
            queue.push([node.left, depth + 1]);
        }
        if (node.right) {
            queue.push([node.right, depth + 1]);
        }
    }
    
    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