[Transformation of in-order traversal] 538. Convert binary search tree to cumulative tree

538. Convert binary search tree to cumulative tree

Problem-solving ideas

  • Transforming the in-order traversal algorithm
  • Because the results of in-order traversal are all sorted in ascending order, then if the right subtree is traversed first and then the left subtree is traversed, the result will be in descending order.
  • Finally, we set a variable to accumulate all the intermediate values, and the result is the value of all nodes larger than the current node.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
    
    
        // 改造中序遍历算法
        traverse(root);
        return root;
    }

    void traverse(TreeNode root){
    
    
        if(root == null){
    
    
            return;
        }
        traverse(root.right);
        sum += root.val;// 每次叠加最大值  比他大的所有节点

        // 将BST 转化为累加树
        root.val = sum;
        traverse(root.left);
    }
}

Guess you like

Origin blog.csdn.net/qq_44653420/article/details/133494112
Recommended