class Solution {
List<TreeNode> arr;
public TreeNode convertBST(TreeNode root) {
arr = new ArrayList<>();
dfs(root);
for(int i = arr.size() - 2;i >= 0;i--){
arr.get(i).val += arr.get(i + 1).val;
}
return root;
}
public void dfs(TreeNode root){
if(root == null) return;
dfs(root.left);
arr.add(root);
dfs(root.right);
}
}
这真的是中等题嘛,秒过。
看了一下强中自有强中手。。。
class Solution {
public TreeNode convertBST(TreeNode root) {
dfs(root, 0);
return root;
}
private int dfs(TreeNode root, int sum){
//sum为该节点右边的所有节点的值的总和(所有比该节点大的节点)
if(root == null){
return sum;
}
//累加操作
root.val += dfs(root.right, sum);
//将累加后的结果传递给左边节点
return dfs(root.left, root.val);
}
}
利用了反向中序遍历,这样就是从大到小遍历,当前节点的值就是累加它自己和它的右子树的和。