题目描述

方法思路
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;
}
}

博客包含题目描述和方法思路两部分。方法思路有两种,一是递归加中序遍历,二是对上述方法进行优化,为解决相关问题提供了不同的信息技术思路。
371

被折叠的 条评论
为什么被折叠?



