法1:反中序遍历(使用全局变量)
注意:Java中函数中传递int变量是值传递,不是引用传递!!!所以需要定义全局变量!!!
class Solution {
public int preSum = 0;
public TreeNode convertBST(TreeNode root) {
if (root == null) {
return root;
}
convert(root); // 右-根-左
return root;
}
public void convert(TreeNode root) {
if (root == null) {
return;
}
convert(root.right);
preSum += root.val;
root.val = preSum;
convert(root.left);
}
}
法2:反中序遍历(不用全局变量)
class Solution {
public TreeNode convertBST(TreeNode root) {
if (root == null) {
return root;
}
convert(root, 0);
return root;
}
public int convert(TreeNode root, int preSum) {
if (root == null) {
return preSum;
}
root.val = convert(root.right, preSum) + root.val;
return convert(root.left, root.val);
}
}