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 #52

Open
sl1673495 opened this issue Jun 4, 2020 · 0 comments
Open

二叉树的右视图-199 #52

sl1673495 opened this issue Jun 4, 2020 · 0 comments
Labels

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jun 4, 2020

199.二叉树的右视图

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

示例:

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

   1            <---
 /   \
2     3         <---
 \     \
  5     4       <---

https://leetcode-cn.com/problems/binary-tree-right-side-view

思路

基本上还是二叉树 BFS 的标准模板套上去就好了,只是取值的时候每一层取最右边的值,也就是从左到右遍历的时候记录到的最后一个值即可。

let rightSideView = function (root) {
  if (!root) return []
  let queue = [root]
  let res = []
  while (queue.length) {
    let len = queue.length
    let last
    for (let i = 0; i < len; i++) {
      let node = queue.shift()
      if (node.left) {
        queue.push(node.left)
      }
      if (node.right) {
        queue.push(node.right)
      }
      if (node.val !== undefined) {
        last = node.val
      }
    }
    res.push(last)
  }
  return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant