leetcode 538. 把二叉搜索樹轉換爲累加樹 & 1038. 從二叉搜索樹到更大和樹

【題目】538. 把二叉搜索樹轉換爲累加樹 & 1038. 從二叉搜索樹到更大和樹

給定一個二叉搜索樹(Binary Search Tree),把它轉換成爲累加樹(Greater Tree),使得每個節點的值是原來的節點值加上所有大於它的節點值之和。

例如:

輸入: 原始二叉搜索樹:
              5
            /   \
           2     13

輸出: 轉換爲累加樹:
             18
            /   \
          20     13

注意:本題和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同

【解題思路1】中序遞歸

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root != null) {
            convertBST(root.right); //一直地軌到最右邊的結點
            sum += root.val; //sum從最大值開始累加
            root.val = sum; 
            convertBST(root.left);
        }
        return root;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章