[LeetCode] 538. Convert BST to Greater Tree
Given the root
of 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.
As a reminder, a binary search tree is a tree that satisfies these constraints:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Note: This question is the same as 1038: https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/
Example 1:
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
Example 2:
Input: root = [0,null,1] Output: [1,null,1]
Example 3:
Input: root = [1,0,2] Output: [3,3,2]
Example 4:
Input: root = [3,2,4,1] Output: [7,9,4,10]
Constraints:
- The number of nodes in the tree is in the range
[0, 104]
. -104 <= Node.val <= 104
- All the values in the tree are unique.
root
is guaranteed to be a valid binary search 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 public TreeNode convertBST(TreeNode root) { 18 helper(root); 19 return root; 20 } 21 22 int sum = 0; 23 24 private void helper(TreeNode root) { 25 if (root == null) { 26 return; 27 } 28 helper(root.right); 29 sum += root.val; 30 root.val = sum; 31 helper(root.left); 32 } 33 }
相关题目
538. Convert BST to Greater Tree
1038. Binary Search Tree to Greater Sum Tree - 一模一样