您的位置:首页 > 其它

Convert BST to Greater Tree

2017-05-16 15:18 477 查看
问题描述:

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


解题思路:

题目要实现树上节点数值变为原数值加上所有比自己大的数值,形成一个比原来的树更大的树。用sum储存某些节数值的加和,根节点等于本身加右子树上的所有数值,左子树上的数值等于根节点的数值加右子树的数值再加本身数值,右子树的数值等于本身数值加子树上比自己大的数值。

代码实现:

/**

 * 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

     */

    int sum=0;

    TreeNode* convertBST(TreeNode* root) {

        // Write your code here

        if(root==NULL) return NULL;

        else{

            convertBST(root->right);

            root->val+=sum;

            sum=root->val;

            convertBST(root->left);

            return root;

        }

    }

};

解题感悟:

这道题逻辑性需求比较强,一开始把convertBST(root->right)和root->val+=sum; sum=root->val;的顺序写反了,出现wrong answer。应该先访问右子树一直到右子树的叶子节点,储存叶子节点的数值,再对双亲节点操作同时储存加和,最后访问左子树对左子树进行操作。

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