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. 二叉树的右视图 #46

Open
webVueBlog opened this issue Sep 12, 2022 · 0 comments
Open

199. 二叉树的右视图 #46

webVueBlog opened this issue Sep 12, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

199. 二叉树的右视图

Description

Difficulty: 中等

Related Topics: , 深度优先搜索, 广度优先搜索, 二叉树

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

示例 1:

输入: [1,2,3,null,5,null,4]
输出: [1,3,4]

示例 2:

输入: [1,null,3]
输出: [1,3]

示例 3:

输入: []
输出: []

提示:

  • 二叉树的节点个数的范围是 [0,100]
  • -100 <= Node.val <= 100 

Solution

Language: JavaScript

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
// var rightSideView = function(root) {
//     const res = []
//     const dfs = (root, depth) => {
//         if (!root) return null
//         if (depth === res.length) {
//             res.push(root.val)
//         }
//         depth++
//         dfs(root.right, depth)
//         dfs(root.left, depth)
//     }
//     dfs(root, 0)
//     return res
// };

var rightSideView = function(root) {
    if (!root) return []
    const q = [root]
    const res = []
    while (q.length) {
        let len = q.length
        while(len--) {
            const n = q.shift()
            if (!len) res.push(n.val)
            n.left && q.push(n.left)
            n.right && q.push(n.right)
        }
    }
    return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant