LeetCode538把二叉搜索树转换为累加树(递归 反中序遍历)

题目链接
在这里插入图片描述
二叉累加树的定义是每个节点等于所有大于自己的节点之和。
首先二叉搜索树的中序遍历是绝对升序的 为012345678
这是我们如果反中序遍历(右根左) 会得到876543210
这是如果把已经遍历到的值累计加到下一个遍历的节点上就可以得到二叉累加树

    int sum = 0;//维护一个全局的和
    public TreeNode convertBST(TreeNode root) {
    
    
        dismid(root);
        return root;
    }
    public void dismid(TreeNode node){
    
    
        if (node == null) return ;
        dismid(node.right);//向右遍历
        node.val += sum;//加上当前节点前面的和
        sum = node.val;//更新和
        dismid(node.left);//向左遍历
    }

猜你喜欢

转载自blog.csdn.net/qq_43434328/article/details/114764932