您的位置:首页 > 其它

convert bst to greater tree

2017-05-18 17:22 417 查看
问题描述:

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。                                 

实现思路:

利用递归,左子树加上它本身和根节点和右子树的值,根节点再加上右子树的值,右子树不变。

实现代码:

/**

 * 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:

std::vector<int> v;

    /**

     * @param root the root of binary tree

     * @return the new root

     */

    TreeNode* convertBST(TreeNode* root) {

        // Write your code here

        int sum=0;

        convert(root,sum);

        return root;

    }

    void convert(TreeNode *root,int &sum)

     {

          if(root!=NULL)

          {convert(root->right,sum);

          root->val+=sum;

          sum=root->val;

          convert(root->left,sum);

          }

     }

};

感想:

利用递归,和二叉排序树的性质
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: