538. Convert BST to Greater Tree

2017-10-01  本文已影响0人  namelessEcho

本题的意思其实就是要你求比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);
    }
   
}
上一篇下一篇

猜你喜欢

热点阅读