1:问题描述
刷新一棵树,每个节点的值等于所有比他大的节点值之和加上她本身。
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
Given a binary search Tree `{5,2,3}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
2:解题思路:
一颗二叉排序树具有特殊的性质,中序遍历之后就是将所有节点值从个小到大排序,更新一棵二叉树就要从他的最右开始更新,先确定右子树的值,右子树的值等于S+他本身的值,将值保存在S中,在确定根结点的值,根结点的值等于S+根节点本身的值,再将这个值保存在S里面,最后确定左子树的值,左子树的值等于S+左子树本身的值。
3:解题代码/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @return the new root
*/
int s=0;
TreeNode* convertBST(TreeNode* root) {
// Write your code here
if(root==NULL)return NULL;
convertBST(root->right);
root->val=s+root->val;
s=root->val;
convertBST(root->left);
return root;
}
};
4:解体感想
这个题真的好难,自己读了好半天才看懂题意,但是这个题解题思路真的很难想,自己用了两节课想了很多想法但是实施起来很困难,自己还是一看就看出来根本行不通,最后问了问同学,给讲了讲,最后理解了,自己已经很多天没写过代码,对理解题还有理解代码就思考的很慢,平时还是要多做题,培养思想。
本文介绍了一种将二叉搜索树转换为大于其所有节点值之和的特殊树的方法。利用二叉排序树的特性,通过递归地从右子树开始更新节点值,最终实现整棵树的转换。
332

被折叠的 条评论
为什么被折叠?



