44 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]

Constraints:

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.

分析

題意:從右到左、下到上累加和,賦給當前節點。

觀察後可知,遍歷順序爲“右、根、左”,因此,以這個爲一個“單元”,設計遞歸算法即可。

解答

class Solution {
	// 記錄當前求和值
    int sum=0;
    public TreeNode bstToGst(TreeNode root) {
        if(root==null) return null;
        // 遍歷右
        bstToGst(root.right);
        // 遍歷根
        sum+=root.val;
        root.val=sum;
        // 遍歷左
        bstToGst(root.left);
        return root;
    }
}

在這裏插入圖片描述

評論區的答案跟我的一樣。

遞歸小結

這類遞歸問題,找出一個符合條件的最小遞歸單元進行調試即可。

理解遞歸其實很簡單,高中的時候都學過數學歸納法,我當初理解遞歸就是類比數學歸納法。

數學歸納法的常見套路就是
1.當n=1時,顯然成立.
2.假設當n=k時(把式中n換成k,寫出來)成立, 則當n=k+1時, 該式也成立。

按我的理解,上面這就是一個“遞推最小單元”,也就是“遞歸最小單元”。只要上面的最小單元成立,那麼遞歸無數層,都是成立的。

寫遞歸算法,就得找出一個最小單元,對其寫一個算法,然後進行遞歸。(區別就在於,設計算法的時候需要把遞歸的步驟以及特徵考慮進去。)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章