538 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.

Example:

Input: The root of a Binary Search Tree like this:
5
/ \
2 13

Output: The root of a Greater Tree like this:
18
/ \
20 13

解釋下題目:

給定一顆二分搜索樹,對(duì)每個(gè)節(jié)點(diǎn)進(jìn)行如此操作:將所有比它大的數(shù)字加起來(lái),加到它上面

1. 遞歸

實(shí)際耗時(shí):xxms

int globalSum = 0;

public TreeNode convertBST(TreeNode root) {
    convert(root);
    return root;
}

public void convert(TreeNode cur) {
    if (cur == null) {
        return;
    }
    convert(cur.right);
    cur.val += globalSum;
    globalSum = cur.val;
    convert(cur.left);
}

??思路:首先確定這是一個(gè)二分搜索樹,所以大小其實(shí)很容易判斷,只需要一直往右走,就能找到最大的那個(gè),而最大的那個(gè)是不需要加任何數(shù)字的;然后找到次小的,這個(gè)次小的就需要加上最大的那個(gè)數(shù)字了。以此進(jìn)行遞歸即可得到最后的解。

時(shí)間復(fù)雜度O(n) n為節(jié)點(diǎn)數(shù)
空間復(fù)雜度O(n)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容