Tcdian / keep

今天不想做,所以才去做。
MIT License
5 stars 1 forks source link

538. Convert BST to Greater Tree #329

Open Tcdian opened 3 years ago

Tcdian commented 3 years ago

538. Convert BST to Greater Tree

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

Example

Input: The root of a Binary Search Tree like this:
              5
            /   \
           2     13

Output: The root of a Greater Tree like this:
             18
            /   \
          20     13
Tcdian commented 3 years ago

Solution

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var convertBST = function(root) {
    let preSum = 0;
    travel(root);
    return root;

    function travel(root) {
        if (root === null) {
            return;
        }
        travel(root.right);
        root.val += preSum;
        preSum = root.val;
        travel(root.left);
    }
};
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function convertBST(root: TreeNode | null): TreeNode | null {
    let preSum = 0;
    travel(root);
    return root;

    function travel(root: TreeNode | null) {
        if (root === null) {
            return;
        }
        travel(root.right);
        root.val += preSum;
        preSum = root.val;
        travel(root.left);
    }
};