538题:
问题链接:https://leetcode.com/problems/convert-bst-to-greater-tree/description/
题目:
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.
给定一个二叉搜索树(BST),将它的节点值变成本身与所有比之大的节点值之和,从而转换成更大的树。
题目要求很明确,思路也比较清晰。我刚开始的思路是用一个递归求出所有比某个节点值大的值之和suml,然后加上本身的值,就是更新之后的树的节点值,然后遍历整棵树,得到最后结果。其中发生了几件事情。第一,在复制树的时候,新树没有用&引用,导致新树创建不成功。第二,在复制树的时候,当原树节点为root=NULL的时候进行了return,没有将新树root1 = NULL,导致遍历新树的时候无法使用root1 = NULL作为跳出递归的条件。第三,外部定义的suml在求得一个节点值之后没有重置为零。
/**
* 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) {
TreeNode* root1 = NULL;
copyBST(root,root1);
return convert(root,root1);
}
void copyBST(TreeNode* root,TreeNode* &root1)//将原树拷贝一份用来更新节点值
{
if(!root)
return ;
else
{
root1 = new TreeNode(NULL);
root1->val = root -> val;
copyBST(root->left,root1->left);
copyBST(root->right,root1->right);
}
}
int suml = 0;
int countsuml(TreeNode* root, int a)//求得每一个节点值对应更新的值
{
if(!root)
return 0;
if(root->val > a)
suml+=root->val;
int left = countsuml(root->left,a);
int right = countsuml(root->right,a);
//suml=suml+left+right;
return suml+a;
}
TreeNode* convert(TreeNode* root, TreeNode* root1)//遍历整棵树
{
if(!root)
return root;
suml = 0;
root->val = countsuml(root1,root->val);
convert(root->left,root1);
convert(root->right,root1);
return root;
}
};
提交之后发现这样做时间复杂度和空间复杂度都比较高。提交后看了看排名靠前的算法,发现自己没有考虑二分查找树的优势。将二分查找树按照中序遍历反向打出,则可得到降序排列的数组,最大的加上零,例如13=13+0,后一个加上前面的和,18 = 13+5, 20 = 18 + 2。又不用额外创建一棵树。
/**
* 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) {
if(root == NULL){
return root;
}
if(root->right != NULL){
convertBST(root->right);
}
sum += root->val;
root->val = sum;
convertBST(root->left);
return root;
}
};