Convert BST to Greater Tree

問題描述:

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
     */
     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);
         
     }
     }
    TreeNode* convertBST(TreeNode* root) {
        int sum;
        SUM(root,sum);
        return root;
            // Write your code here
    }
};

感悟:

在寫代碼前要考慮全面,開始沒有考慮到後續遍歷。



發佈了49 篇原創文章 · 獲贊 0 · 訪問量 5003
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章