LeetCode BST Topic 538 Converting a binary search tree to an accumulative tree java

Question details

Given the root node of the binary search tree, the node value of the tree is different, please convert it to a greater sum tree, so that the new value of each node node is equal to or greater than node in the original tree. The sum of the values ​​of val.
Insert picture description here

Problem-solving ideas and codes

This question is BST. We have to be clear about BST. In-order traversal is to output an ordered sequence of numbers from small to large. (For the middle-order traversal, BST can see the pre-order, middle-order, post-order traversal of the binary tree (& BST), recursion and iteration, java )
Then the new value of each point here is the current value + all values ​​greater than the current value , If we have a sequence of ordinal numbers, the new value of the point is: starting from the old value and accumulating to the end.
Of course, we don't have to traverse the middle order first, then access the array, and then traverse the modification again, which is too troublesome.
We directly accumulate from the last of the ordinal sequence to the old value.
How to go from back to front? Just flip the mid-order traversal.

In the middle order traversal, we are

void dfs(TreeNode root) {
    
    
    dfs(root.left);
    visit(root);
    dfs(root.right);
}

Here we reverse it, put right first, then left.

The specific code is as follows:

class Solution {
    
    
    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
    
    
        //每个数的新值就是其父节点、父节点的右子树(如果有父节点的话)+右子节点的和
        //中序遍历的话是从小到大的有序对吧,如果我把中序的左和右改一下,是不是就是从大到小遍历了
        //然后每个点的值就是自己+之前的sum
        //应该就是这样
        // int sum = 0;
        dfs(root);
        return root;
    }

    public void dfs(TreeNode node){
    
    
        if(node==null){
    
    
            return;
        }
        dfs(node.right);
        sum += node.val;
        node.val = sum;
        dfs(node.left);
        return;
    }
}

Guess you like

Origin blog.csdn.net/qq_34687559/article/details/109393292