leetcode(538):把二叉搜索树转换为累加树

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

例如:

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

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

注意:本题和 1038: https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/ 相同

思路:

通过递归实现。

通过调用栈回到之前的节点

class Solution {
    private int num = 0;
    
    public TreeNode convertBST(TreeNode root) {
        if (root != null) {
            //遍历右子树
            convertBST(root.right);
            //遍历顶点
            root.val = root.val + num;
            num = root.val;
            //遍历左子树
            convertBST(root.left);
            return root;
        }
        return null;
    }
}

  

原文地址:https://www.cnblogs.com/wangzepu/p/12911243.html