- 描述: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
- 分析:将一棵二叉搜索数的每个节点转化为,这个节点的值加上比这个节点大的其他所有节点的值之和。
- 思路一:dfs深度优先搜索。由于题目中所给的是一棵二叉搜索树,因此可以利用二叉搜索树的规则,即node.left<node<=node.right。根据这个规则每次从右子树开始深度搜索。
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
if (root == NULL) return NULL;
dfs(root, 0);
return root;
}
private:
int dfs(TreeNode* root, int sum) {
if (root -> right != NULL) sum = dfs(root -> right, sum);
root -> val += sum;
if (root -> left != NULL) return dfs(root -> left, root -> val);
else return root -> val;
}
};