1038. Binary Search Tree to Greater Sum Tree

題目

https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/

這是一道關於二叉樹,二叉搜索樹的題目。

Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.

As a reminder, a binary search tree is a tree that satisfies these constraints:

The left subtree of a node contains only nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.

Example 1:
在這裏插入圖片描述

Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

Note:

The number of nodes in the tree is between 1 and 100.
Each node will have value between 0 and 100.
The given tree is a binary search tree.

解答

題目的意思是,給你一個BST,讓你修改BST的每一個node的值,它要滿足這樣的條件,這個新的值是一個求和,這個和是大於等於這個當前節點的求和。

所以我們來看一看上面那個示例中一小部分樹吧

爲什麼8是8呢?因爲8是最葉子的節點,所以大於等於8的只有8自己了。
爲什麼7是15呢?因爲大於等於7的節點有7和8,他們的和爲15。
爲什麼6是21呢?因爲大於等於6的有6,7,8,所以他們的和爲15。
爲什麼5是26呢?因爲大於等於5的節點有5,6,7,8,所以……

顯然,直覺告訴我們,需要先處理右邊的節點,再處理中間的節點,再處理右邊的節點。

我們直接考慮一個最小的情況好了,我發現考慮最小的情況是最容易理解全貌的。

在這裏插入圖片描述
現在,如上圖所示,我們只有567三個節點。

顯然7應該被先處理,它還是7。
接着處理6,它應該加上7,也就是右邊的節點,或者說,上一次的累加值。
接着處理5,它應該加上一次的累加值。

這裏需要一個累加值用來記錄上一次的求和。
在這個簡單的例子中,一開始爲0,因此7還是7,累加值變爲7.
接着6變成了13,累加值變爲13.
接着5變成了18,累加值變爲了18.

這個18可以被理解爲這個小樹變成了一個18的節點。這樣就可以被遞歸下去了。

因此,代碼如下:

class Solution {
    int pre = 0;
    
    public TreeNode bstToGst(TreeNode root) {
        if (root != null) {
            bstToGst(root.right);
            pre = root.val = root.val + pre;
            bstToGst(root.left);
        }
        return root;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章