[二叉树BST]!538. Convert BST to Greater Tree

题目: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.
给一个二叉搜索树,把每个node值换位它自身+比它大的所有value值。

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本来就有左<中<右的性质。

从微观上来讲,BST的每个节点都大于其左节点,且小于其右节点。
从宏观上来将,BST的每个节点都大于其左子树的每个节点,且小于其右子树的每个节点。

第一次提交。add是当前截止的累加值,注意是global。从右往左算add。

class Solution {
int add = 0;
    public TreeNode convertBST(TreeNode root) {

 if(root == null){return null;}
        if(root.right == null && root.left == null){   //叶子
            int t = add;
            add = root.val + add;
            root.val = root.val + t;
        }else{
            if(root.right != null){
                root.right = convertBST(root.right);    //先递归右子树。
            }
                int t = add;
                add = root.val + add;     //+中间value
                root.val = root.val +t;
            if(root.left != null){
                root.left = convertBST(root.left);      //+左子树递归
            }
        }
        return root;
    }
}

第二次提交:

class Solution {
    int add = 0;
    public TreeNode convertBST(TreeNode root) {
        if(root == null){return null;}
        convertBST(root.right);           // Right
            root.val = root.val + add;     //Root
            add = root.val;
        convertBST(root.left);              //Left 
        return root;
        
    }
}
    原文作者:Reflection_
    原文地址: https://www.jianshu.com/p/794d6650d1eb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞