1. 程式人生 > >JavaScript刷LeetCode -- 538. Convert BST to Greater Tree

JavaScript刷LeetCode -- 538. Convert BST to Greater Tree

一、題目

  Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
              5
            /   \
           2     13

Output: The root of a Greater Tree like this:
             18
            /   \
          20     13

二、題目大意

  將給定的二叉樹上的每個節點的值更新為二叉樹上所有大於等於該值的節點之和。

三、解題思路

  對於BST進行中序遍歷,可以得到一個有序佇列,所有對於這道題目,可以逆中序遍歷的方式,從最大值的節點向前累加。

四、程式碼實現

const convertBST = root => {
  let sum = 0
  dfs(root)
  return root
  function dfs (root) {
    if (!root) {
      return
    }
    dfs(root.right)
    root.val += sum
    sum = root.val
    dfs(root.left)
  }
}

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