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
C Solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void inorder(struct TreeNode *root, int *sum) {
if (root->right) inorder(root->right, sum);
*sum = root->val += *sum;
if (root->left) inorder(root->left, sum);
}
struct TreeNode* convertBST(struct TreeNode* root) {
if (!root) return 0;
int sum = 0;
inorder(root, &sum);
return root;
}
Python Solution:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def convertBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return
def inorder(root, sum):
if root.right:
sum = inorder(root.right, sum)
root.val += sum
sum = root.val
if root.left:
sum = inorder(root.left, sum)
return sum
inorder(root, 0)
return root
Summary:
*sumandinorder()is necessary
LeetCode: 538. Convert BST to Greater Tree





近期评论