欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

538. Convert BST to Greater Tree && 1038. Binary Search Tree to Greater Sum Tree

程序员文章站 2022-04-24 21:56:08
...

Problem

538

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example

538. Convert BST to Greater Tree && 1038. Binary Search Tree to Greater Sum Tree

1038

Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val.

As a reminder, a binary search tree is a tree that satisfies these constraints:

  • The left subtree of a node contains only nodes with keys less than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • Both the left and right subtrees must also be binary search trees.

Constraints:

  • The number of nodes in the tree is between 1 and 100.
  • Each node will have value between 0 and 100.
  • The given tree is a binary search tree.

Example

538. Convert BST to Greater Tree && 1038. Binary Search Tree to Greater Sum Tree

Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]

Solution

二叉搜索树的反向中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int prev = 0;
    TreeNode* convertBST(TreeNode* root) {
        if(!root)
            return NULL;
        convertBST(root->right);

        root->val += prev;
        prev = root->val;

        convertBST(root->left);


        return root;


    }

    
};