把二叉搜索树转换为累加树

117 阅读1分钟

LeetCode 538

leetcode-cn.com/problems/co…

解题思路

因为本题提供的树是二叉搜索树,所以满足左子树的值小于根节点小于右子树,所以我们可以从大值节点往小值节点遍历,这样省去记录全部节点的值再进行判断然后累加。往小值方向遍历,就可以一直累加之前遍历的相对当前节点的大值的总和,所以只需要进行中序遍历的反向,即右根左,然后累加过程中记录累加总和,方便给后面的小值赋值。

代码如下

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int preVal = 0;

    public TreeNode convertBST(TreeNode root) {
        if(root == null) {
            return null;
        }
        convertBST(root.right);
        root.val += preVal;
        preVal = root.val;
        convertBST(root.left);
        return root;
    }
}