538-Convert BST to Greater Tree
Description
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
問題描述
給定二叉排序樹, 轉換該二叉排序樹, 使得其每個節點的值為大於它的值的節點值之和
問題分析
“傳統的”中序遍歷, 獲取的二叉排序樹的遞增值序列, 那麼我們不妨轉換下思想, 將遍歷左右子樹的順序顛倒, 使得遍歷的值為由大到小排列, 通過sum累計值, 將其賦值給遍歷的當前節點即可
注意一下, 對於二叉排序樹來說, 中序遍歷通常比較重要(遞增值序列), 一般遇到問題可以優先考慮
解法1
/*
這種解法不太優雅
首先通過"傳統的"中序遍歷獲取遞增值序列, 將該序列儲存在一個List中, 然後逆序累加
*/
class Solution {
private int index;
private List<Integer> res;
public TreeNode convertBST(TreeNode root) {
index = 0;
res = new ArrayList<Integer>();
TreeNode node = root;
inorder(node);
int sum = 0;
for(int i = res.size() - 1;i >= 0;i--){
sum += res.get(i);
res.set(i,sum);
}
node = root;
convert(node);
return root;
}
public void convert(TreeNode root){
if(root == null) return;
convert(root.left);
root.val = res.get(index++);
convert(root.right);
}
public void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
res.add(root.val);
inorder(root.right);
}
}
解法2
//這種解法就是問題分析中的解法
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
public void convert(TreeNode cur) {
if (cur == null) return;
convert(cur.right);
cur.val += sum;
sum = cur.val;
convert(cur.left);
}
}
相關文章
- LeetCode之Convert BST to Greater Tree(Kotlin)LeetCodeKotlin
- 樹-BST基本實現
- [LeetCode] 776. Split BSTLeetCode
- 449-Serialize and Deserialize BST
- 450-Delete Node in a BSTdelete
- [LeetCode] 2275. Largest Combination With Bitwise AND Greater Than ZeroLeetCode
- [LeetCode] 230. Kth Smallest Element in a BSTLeetCode
- 653-Two Sum IV - Input is a BST
- 二叉堆、BST 與平衡樹
- 從BST到LSM的進階之路
- [Leetcode學習-c++&java]Next Greater Element I ~ IIILeetCodeC++Java
- tree
- LeetCode演算法題-Next Greater Element I(Java實現)LeetCode演算法Java
- 二叉排序樹BST及CRUD操作排序
- 學習筆記——二叉平衡樹(BST)筆記
- DSU on Tree
- Rebuild TreeRebuild
- 01 Tree
- Tree Compass
- A - Distance in Tree
- Decision Tree
- 【MySQL(1)| B-tree和B+tree】MySql
- [LeetCode] 1343. Number of Sub-arrays of Size K and Average Greater than or Equal to ThresholdLeetCode
- ORA-00837: Specified value of MEMORY_TARGET greater than MEMORY_MAX_TARGET
- 資料結構☞二叉搜尋樹BST資料結構
- 多路查詢樹:B-tree/b+tree
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- segment tree beats
- Circular Spanning Tree
- B-tree
- B+tree
- tree-shaking
- Walking the File Tree
- Root of AVL Tree
- Tree – Information TheoryORM
- mvn dependency:tree
- Traversals of binary tree
- 用PHP來實現二分搜尋樹(BST)PHP