Leetcode538. 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
解题分析
题目乍一看,很可能被懵住了,在想怎么遍历才能使得左子树的节点的值能够加上右边节点的和。但我们不妨想一下,是否可以将树转化为一个数组,并将其排序?这样我们就可以对数组进行遍历然后依次转化它们的值,最后只需再按顺序将数组元素的值插入到树中就可以了。
我们知道,二叉搜索树有这样一个性质:某个节点的左子树的所有节点的值都会小于该节点,而右子树的所有节点的值都会大于该节点;而中序遍历刚好就是先遍历左子树,再遍历中间节点,最后再遍历右子树。
想到了这一点,问题就解决一大半了。注意中间有一点,我们知道,vector是没有pop_front()的函数的,所以要想删除第一个元素,就必须用迭代器,这显然有点麻烦了;在这里我们做一个小小的变换,将数组颠倒过来,最后再中序遍历往树中插值的时候就可以取出最后一个值并将其pop_back(),这样就省去了一些不必要的麻烦。
源代码
/**
* 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:
TreeNode* convertBST(TreeNode* root) {
if(root == NULL) {
return NULL;
}
int i, j;
vector<int> v;
inorder(root, v);
for(i = 0, j = v.size() - 1; i < j; j--) {
v[i] += v[j];
if(i == j - 1) {
i++;
j = v.size();
}
}
reverse(v.begin(), v.end());
convert(root, v);
return root;
}
void inorder(TreeNode* root, vector<int>& v) {
if(root == NULL) {
return;
}
inorder(root->left, v);
v.push_back(root->val);
inorder(root->right, v);
}
void convert(TreeNode* root, vector<int>& v) {
if(root == NULL) {
return;
}
convert(root->left, v);
root->val = v.back();
v.pop_back();
convert(root->right, v);
}
};
这只是我对这道题的一些想法,有问题还请在评论区讨论留言~