Leetcode 538. 把二叉搜索树转换为累加树
题目链接
https://leetcode.com/problems/convert-bst-to-greater-tree/description/
题目描述
大于它的节点值之和。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。例如:
输入: 二叉搜索树:
              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 {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        convert(root);
        return root;
    }
    
    public void convert(TreeNode root) {
        if (root == null) { return ; }
        convert(root.right);
        root.val += sum;
        sum = root.val;
        convert(root.left);
        
    }
}
                    更多精彩
		
													
													
													
													
	
		
