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

在这里插入图片描述
思路:
二叉搜索树是一棵有序树,其任意根结点的值大于其左结点,且小于右结点的值,需要注意的是本题中所有结点都是严格大于或小于的。基于搜索二叉树的这个性质我们容易想到,要找大于任意根结点的值只需找其右子树,我们可以管理一个全局变量用于记录大于当前结点的所有结点的累加和,并且使用右-根-左的方式对二叉树进行遍历。

//递归
class Solution {
    
    
    int sum=0;
    public TreeNode convertBST(TreeNode root) {
    
    
        if(root!=null){
    
    
            convertBST(root.right);
            sum += root.val;
            root.val = sum;
            convertBST(root.left);
        }    
        return root;
    }
}

//迭代
class Solution {
    
    
    public TreeNode convertBST(TreeNode root) {
    
    
        int sum=0;
        Stack<TreeNode> stack=new Stack<>();
        //工作指针
        TreeNode p=root;
        // stack.push(root);
        while(!stack.isEmpty() || p!=null){
    
    
            if(p!=null){
    
    
                stack.push(p);
                p=p.right;
            }else{
    
    
                p=stack.pop();
                sum+=p.val;
                p.val=sum;
                p=p.left;
            }
        }
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42451178/article/details/107238600