Convert BST to Greater Tree

来源:互联网 发布:创世纪 知乎 编辑:程序博客网 时间:2024/06/18 15:30

题目:

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
思路:如果它是父亲的左孩子,则它的值应为它的值加上它父亲的值以及它的右子树的值,而如果是右孩子的话,就不用加它父亲的值。

代码:

/**
 * 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 NULL;
        if(root->right!=NULL)
           {  root->val=root->val+sum(root->right);
              convertBST(root->right);
           }
        if(root->left!=NULL)
           {   root->left->val=root->val+root->left->val;
               convertBST(root->left);
           }
        return root;
    }
    int sum(TreeNode* root){
        int k=root->val;
        if(root->left!=NULL) k=k+sum(root->left);
        if(root->right!=NULL) k=k+sum(root->right);
        return k;
    }*/
    int sum = 0;
        helper(root, sum);
        return root;
    }
    void helper(TreeNode*& node, int& sum) {
        if (!node) return;
        helper(node->right, sum);
        node->val += sum;
        sum = node->val;
        helper(node->left, sum);
    }
};

感想:我老感觉这道题有问题,因为我第一次提交后,它给出一个例子{1,2,3,4,5,6,7},计算和它的不一样,可是这又明明不是二叉查找树,就算我把它转换成二叉查找树手算后也不对,但换成后来这种算法后就过了,有点莫名其妙。

原创粉丝点击