[LeetCode] 538. Convert BST to Greater Tree

來源:互聯網
上載者:User

標籤:rtb   ike   +=   public   意思   style   tco   大於   put   

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     13Output: The root of a Greater Tree like this:             18            /             20     13

題意:給定一個二叉搜尋樹,把它轉換成為累加樹,使得每個節點的值是原來的節點值加上所有大於它的節點值之和。
做樹的題一定要利用條件,就是特別的給了一個什麼樣的樹,這個樹有什麼特性
二叉搜尋樹的特點是 右>根>左,也就是說中序有序,我們把中序倒過來就正好是從大到小的
什麼意思呢,就是當你遍曆到某個節點的時候,比它大的都已經遍曆完了,我們只需維護一個max就行
class Solution {    private int max = 0;    private void convert(TreeNode root) {        if (root == null)            return;        convert(root.right);        root.val += max;        max = root.val;        convert(root.left);    }    public TreeNode convertBST(TreeNode root) {        convert(root);        return root;    }}

 

 

[LeetCode] 538. Convert BST to Greater Tree

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.