welcome to my blog
LeetCode Top 100 Liked Questions 538. Convert BST to Greater Tree (Java版; 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.
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
class Solution {
public TreeNode
convertBST(TreeNode root
) {
if(root
==null
){
return root
;
}
Stack
<TreeNode> s
= new Stack<>();
int sum
= 0;
TreeNode cur
= root
;
while(!s
.isEmpty() || cur
!=null
){
while(cur
!=null
){
s
.push(cur
);
cur
= cur
.right
;
}
cur
= s
.pop();
sum
+=cur
.val
;
cur
.val
= sum
;
cur
= cur
.left
;
}
return root
;
}
}
class Solution {
private int sum
= 0;
public TreeNode
convertBST(TreeNode root
) {
if(root
==null
){
return root
;
}
convertBST(root
.right
);
sum
+= root
.val
;
root
.val
= sum
;
convertBST(root
.left
);
return root
;
}
}
class Solution {
public TreeNode
convertBST(TreeNode root
) {
core(root
, 0);
return root
;
}
private int core(TreeNode root
, int parentSum
){
if(root
==null
){
return 0;
}
int R
= core(root
.right
, parentSum
);
int tmp
= root
.val
;
root
.val
= root
.val
+ R
+ parentSum
;
int L
= core(root
.left
, root
.val
);
return L
+ tmp
+ R
;
}
}
最开始的错误原因, 估计之后看就看不懂了, 主要是提醒自己得熟练的画图梳理递归逻辑
错误原因:root右子树的考虑了root父节点的信息, 重复了, root右子树应该返回1
第一次做; 考察二叉树遍历; 采用右根左的形式; 涉及到前缀和, 需要很小心; 返回值和直接功能分离
class Solution {
public TreeNode
convertBST(TreeNode root
) {
if(root
==null
)
return null
;
core(root
, 0);
return root
;
}
public int core(TreeNode root
, int preSum
){
if(root
==null
)
return 0;
int rightRes
= core(root
.right
, preSum
);
int old
= root
.val
;
root
.val
= root
.val
+ rightRes
+ preSum
;
int leftRes
= core(root
.left
, root
.val
);
return leftRes
+ old
+ rightRes
;
}
}