题目:
我的解法:两遍递归
在不了解二叉树的基础上,我用笨方法做了一遍,先遍历一遍整个二叉搜索树,将所有的值存到List里,再次遍历整个二叉树,修改每个位置对应的值。(这样做虽然可以正确求解,但是时间复杂度太高)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> nums = new ArrayList<Integer>();
public TreeNode convertBST(TreeNode root) {
if (root==null){
return null;
}
addNum(root);
TreeNode tn = changeVal(root, nums);
return tn;
}
// 遍历每个结点左右子结点的值
public void addNum(TreeNode tn){
nums.add(tn.val);
if(tn.left!=null){
addNum(tn.left);
}
if(tn.right!=null){
addNum(tn.right);
}
}
// 修改每个结点的值
public TreeNode changeVal(TreeNode tn, List<Integer> nums){
int sum = 0;
for(int i=0; i<nums.size(); i++){
if(nums.get(i)>tn.val){
sum = sum + nums.get(i);
}
}
tn.val = tn.val + sum;
if(tn.left!=null){
changeVal(tn.left, nums);
}
if(tn.right!=null){
changeVal(tn.right, nums);
}
return tn;
}
}
官方解法一:反序中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
if(root!=null){
root.right = convertBST(root.right);
root.val += sum;
sum = root.val;
root.left = convertBST(root.left);
}
return root;
}
}
官方解法二:Morris 遍历
class Solution {
public TreeNode convertBST(TreeNode root) {
int sum = 0;
TreeNode node = root;
while (node != null) {
if (node.right == null) {
sum += node.val;
node.val = sum;
node = node.left;
} else {
TreeNode succ = getSuccessor(node);
if (succ.left == null) {
succ.left = node;
node = node.right;
} else {
succ.left = null;
sum += node.val;
node.val = sum;
node = node.left;
}
}
}
return root;
}
public TreeNode getSuccessor(TreeNode node) {
TreeNode succ = node.right;
while (succ.left != null && succ.left != node) {
succ = succ.left;
}
return succ;
}
}