link
思路
首先复习何谓binary search tree
简单来说,所有节点的right hand side值都比自己大;所有节点的left hand side值都比自己小。
根据以上的定义,开始剖析最小单元的binary tree,例如题目的example:
root node为5,我们则先travel它的右子树,因我们知道右子树一定比root node还要大,那么root node的值则需要加上右子树的值。
加完后,观察此node的值(原5,加完后13)对于左子树来说,即是所有比他大的node value的总和了,此时再去travel左子树
C++ solution
/
* 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) {
int sum = 0;
travel(root, sum);
return root;
}
void travel(TreeNode* node, int& sum)
{
if (!node) return ;
travel(node->right, sum); // traveling right-side tree first for accumulating greater-values
node->val += sum; // plus all greater-values from the point of view of root node
sum = node->val; // accumulating the greater-values
travel(node->left, sum); // do the same thing for left-side tree
}
};
原文:大专栏 538. Convert BST to Greater Tree