[LeetCode] 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

Note: This question is the same as 1038: 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 }

 

相关题目

538. Convert BST to Greater Tree

1038. Binary Search Tree to Greater Sum Tree - 一模一样

LeetCode 题目总结

上一篇:搜索树判断


下一篇:[LeetCode] 530. Minimum Absolute Difference in BST