法1:反中序遍历(使用全局变量)
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.pre = 0
def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
self.dfs(root)
return root
def dfs(self, root):
if not root:
return
self.dfs(root.right)
self.pre += root.val
root.val = self.pre
self.dfs(root.left)
Java
注意: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:反中序遍历(不用全局变量)
Java
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);
}
}