1. 程式人生 > >JavaScript刷LeetCode -- 199. Binary Tree Right Side View [Medium]

JavaScript刷LeetCode -- 199. Binary Tree Right Side View [Medium]

一、題目

 &emmsp;Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

  Example:

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

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

二、題目大意

  給定一個二叉樹,想象自己站在它的右側,返回從上到下排序的節點的值。

三、解題思路

  這道題實際上就是分層遍歷二叉樹。

四、程式碼實現

const rightSideView = root => {
  const ans = []
  help(root, 0)
  return ans
  function help (root, index) {
    if (!root) {
      return
    }
    if (ans[index] === undefined) {
      ans[index] = root.val
    }
    help(root.right, index + 1)
    help(root.left, index + 1)
  }
}

  如果本文對您有幫助,歡迎關注微信公眾號,為您推送更多內容,ε=ε=ε=┏(゜ロ゜;)┛。