描述
给定二叉搜索树(BST),将其转换为更大的树,使原始BST上每个节点的值都更改为在原始树中大于等于该节点值的节点值之和(包括该节点)。
您在真实的面试中是否遇到过这个题?
是
样例
Given a binary search Tree `{5,2,13}`:
5
/ \
2 13
Return the root of new tree
18
/ \
20 13
中序遍历右子树的顺序,下一个节点的值的自己原来的值加上上一个节点的值,所以只需要有一个变量来保存上一个节点值是多少即可。
/**
* 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
*/
TreeNode * convertBST(TreeNode * root) {
// write your code here
if(root==NULL) return root;
calculate(root);
return root;
}
void calculate(TreeNode * root){
if(root->right!=NULL) calculate(root->right);
root->val+=m_val;
m_val=root->val;
if(root->left!=NULL) calculate(root->left);
}
private:
int m_val=0;
};