烟_火
人间烟火何不尝

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

例如:

输入: 原始二叉搜索树:
  5
/ \
2 13

输出: 转换为累加树:
  18
/ \
20 13

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

 

posted on 2020-03-11 22:23  段流儿  阅读(123)  评论(0编辑  收藏  举报