您的位置:首页 > 其它

Convert BST to Greater Tree

2017-05-18 17:05 591 查看
1.问题描述

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


2.解题思路

定义一个求和的新的函数,进行后序遍历的时候进行累加求和,以此将当前的累加和与当前节点相加赋给当前节点。

3.代码实现

/**

 * 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

        int sum;

        SUM(root,sum);

        return root;

    }

    void SUM(TreeNode*root,int &sum)

    {

        if(root==NULL)

        return ;

        else{

            SUM(root->right,sum);

            root->val+=sum;

            sum=root->val;

            SUM(root->left,sum);

        }

    }

};

4.感想

本题是将节点值比当前节点大的节点都加到当前节点,所以递归的时候按后序遍历求和。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: