题目描述
方法思路
Approach1: recursive + inorder traversal
class Solution {
//Runtime: 10 ms, faster than 28.05%
//Memory Usage: 39.6 MB, less than 71.62%
Stack<TreeNode> stk;
public TreeNode convertBST(TreeNode root) {
stk = new Stack<>();
int sum = 0;
inorder(root);
while(!stk.isEmpty()){
stk.peek().val += sum;
sum = stk.pop().val;
}
return root;
}
public void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
stk.push(root);
inorder(root.right);
}
}
Approach2: 上述方法的优化
class Solution {
//Runtime: 5 ms, faster than 100.00%
//Memory Usage: 39.7 MB, less than 69.82%
private int sum = 0;
public TreeNode convertBST(TreeNode root) {
if (root != null) {
convertBST(root.right);
sum += root.val;
root.val = sum;
convertBST(root.left);
}
return root;
}
}