1. 程式人生 > 實用技巧 >Leetcode538.-Convert BST to Greater Tree-Easy

Leetcode538.-Convert BST to Greater Tree-Easy

題目:

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.

思路:

每個結點值加上所有比它大的結點值總和當作新的結點值。

初始化sum值 = 0

因為inorder traversal (left->root->right)結果是non decreasing 遞增數列,那麼逆過來right->root->left

,就可以得到遞減數列, 每遍歷到一個結點更新sum值,並將更新後的sum值賦給當前結點,從而保證,在當前結點,所有比他大的結點都訪問過了,並且sum值就是所有比他大的結點值的總合。

程式碼:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 
*/ class Solution { private int sum = 0; public TreeNode convertBST(TreeNode root) { dfs(root); return root; } private void dfs(TreeNode root) { if(root == null) return; dfs(root.right); sum += root.val; root.val = sum; dfs(root.left); } }