给定一颗二叉树,从右侧中序遍历,然后不断的加和就可以了。
一次ac
void converBSTImpl(TreeNode* root, int& value)
{
if (root)
{
if (root->right)
{
converBSTImpl(root->right, value);
}
value = value + root->val;
root->val = value ;
if (root->left)
{
converBSTImpl(root->left, value);
}
}
}
// 538. Convert BST to Greater Tree
TreeNode* Solution::convertBST(TreeNode* root)
{
int max = 0;
if (root)
{
converBSTImpl(root, max);
}
return root;
}
Runtime: 44 ms, faster than 97.20% of C++ online submissions for Convert BST to Greater Tree.
Memory Usage: 23.5 MB, less than 100.00% of C++ online submissions for Convert BST to Greater Tree.