美文网首页
538. Convert BST to Greater Tree

538. Convert BST to Greater Tree

作者: namelessEcho | 来源:发表于2017-10-01 21:02 被阅读0次

本题的意思其实就是要你求比Node.val大的所有值的和,利用BST是有序的以及在中序遍历下访问到的值任然是有序的这个性质,从右侧为先开始中序遍历求sum,问题得到了解决。

例如:[5,3,7,1,4,6,8]


tree

对于3节点来说当运行到他时sum=25,此时向右递归的过程中sum继续相加,最后得到了稳定的结果。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int sum =0;
    public TreeNode convertBST(TreeNode root) {
        search(root);
        return root;
    }
    private void search (TreeNode root )
    {
        if(root==null)return ;
        search(root.right);
        root.val+=sum;
        sum=root.val;
         search(root.left);
    }
   
}

相关文章

网友评论

      本文标题:538. Convert BST to Greater Tree

      本文链接:https://www.haomeiwen.com/subject/myiaextx.html