Convert BST to Greater Tree-LintCode

描述:

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
思路:
基於二叉排序樹的性質,即根節點的左子樹上的節點都小於根節點,右子樹上的節點都大於根結點。
所以這個題就需要從最右邊的葉子節點開始訪問,因爲它是整棵樹中最大的節點,訪問順序爲 右子樹->根節點->左子樹。
在訪問一個節點時依序加上之前訪問過的節點,誰讓那些節點都比它大呢!
AC代碼:
/**
 * 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;
    void add(TreeNode* root)
    {
        if(root==NULL)
            return ;
        add(root->right);
        root->val=root->val+sum;
        sum=root->val;
        add(root->left);
    }
    TreeNode* convertBST(TreeNode* root) {
        // Write your code here
        add(root);
        return root;
    }
};



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章