[LeetCode] 538. Convert BST to Greater Tree
阿新 • • 發佈:2020-09-21
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
Note:This question is the same as1038:https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
把二叉搜尋樹轉換為累加樹。題意是給一個BST二叉搜尋樹,請你改動這個BST,使得每個節點的值更新為本身的值 + 所有比他大的值的和。
思路是反過來的中序遍歷。一般的中序遍歷是左根右,但是對於每個節點來說,需要知道比自己大的節點才能更新自己的值,所以採取先更新最大的節點的值,因為沒有節點比他更大了。這樣倒序從大到小遍歷節點,每次可以把所有比當前節點大的節點的值並且可以累加給再小的節點。
時間O(n)
空間O(n)
Java實現
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val;11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 int sum = 0; 18 19 public TreeNode convertBST(TreeNode root) { 20 if (root != null) { 21 convertBST(root.right); 22 sum += root.val; 23 root.val = sum; 24 convertBST(root.left); 25 } 26 return root; 27 } 28 }