[LeetCode] 538. The binary search tree into the tree accumulated

topic

Given a binary search tree (Binary Search Tree), it is converted into accumulated trees (Greater Tree), such that the value of each node is the original value of the node plus all its node value is greater than the sum.

E.g:

Input: binary search tree:

              5
            /   \
           2     13

Output: convert accumulated tree:

             18
            /   \
          20     13

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/convert-bst-to-greater-tree
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

answer

  • I.e., the use of anti preorder traversal order left Une
  • So just traversed again, because the nature of binary search trees guarantee is descending traverse, each update accumulated value and added value to update the node on the current node.

Code

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private 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;
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11809632.html