Leetcode 538. 把二叉搜索树转换为累加树

题目链接

https://leetcode.com/problems/convert-bst-to-greater-tree/description/

题目描述

大于它的节点值之和。

例如:

输入: 二叉搜索树:
              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);
        
    }
}
原文地址:https://www.cnblogs.com/xiagnming/p/9700216.html