Convert BST to Greater Tree

来源:互联网 发布:邮政网络培训学院登录 编辑:程序博客网 时间:2024/06/06 20:46

问题描述:给定一个二叉搜索树(BST),将其转换为更大的树,这样每一个原始BST的关键是改变原来的关键+所有键大于原BST的关键。

样例

Given a binary search Tree `{5,2,3}`:

              5            /   \           2     13

Return the root of new tree

             18            /   \          20     13
解题思路:将当前结点右边的节点值用递归的方式全加起来,然后赋值给当前结点,最后成新的树 。

实验代码:

class Solution {
public:
    /**
     * @param root the root of binary tree
     * @return the new root
     */
     int a=0;
    TreeNode* convertBST(TreeNode* root) {
        // Write your code here
       
        if(root==NULL)
        return NULL;
        add(root);
        return root;
    }
   void add(TreeNode* root)
   {    
        if(root==NULL) 
           return;
        if(root->right!=NULL)
           add(root->right);
        a=root->val+a;
        root->val=a;
        if(root->left!=NULL)
           add(root->left);
   }
};

个人感想:定义的a必须是全集变量。

原创粉丝点击