LN : leetcode 538 Convert BST to Greater Tree

时间:2023-03-09 18:38:53
LN : leetcode 538 Convert BST to Greater Tree

lc 538 Convert BST to Greater Tree


538 Convert BST to Greater Tree

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:

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

递归 Accepted

二叉搜索树的特点是对于任一节点来说,其左子树结点都比其小,其右子树结点都比其大。所以对于本题,只需利用递归,先访问最右结点,以一个sum值记录从大到小的原数值和。

/**
* 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 sum = 0;
TreeNode* convertBST(TreeNode* root) {
travel(root);
return root;
}
void travel(TreeNode* root) {
if (!root) return;
if (root->right) travel(root->right);
root->val = (sum += root->val);
if (root->left) travel(root->left);
}
};