题:
方法1:哈希表
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public TreeNode convertBST(TreeNode root) {
if (root == null) return null;
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
dfsCreateMap(root, map);
dfsCreateSumTree(root, map);
return root;
}
public static void dfsCreateMap(TreeNode root, Map<Integer, Integer> map) {
map.put(root.val, 0);
// 遍历map里已经有的数value,如果当前数val >= value ,则map对应的value+=val
// 因为是二叉搜索树,所以采用左中右的顺序进行遍历
//递归的看左子树
if (root.left != null)
dfsCreateMap(root.left, map);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
Integer value = entry.getKey();
if (root.val >= value) {
map.replace(entry.getKey(), entry.getValue() + root.val);
}
}
//递归的看右子树
if (root.right != null)
dfsCreateMap(root.right, map);
}
public static void dfsCreateSumTree(TreeNode root, Map<Integer, Integer> map) {
root.val = map.get(root.val);
//递归的看左子树
if (root.left != null)
dfsCreateSumTree(root.left, map);
//递归的看右子树
if (root.right != null)
dfsCreateSumTree(root.right, null);
}
方法2:直接搞,优化一下,根本不需要哈希表
public TreeNode convertBST(TreeNode root) {
if (root == null) return null;
// 法二,直接左中右的顺序遍历,搞一个当前累加和
// 先找到最右面,就是最小的值
int[] curSum = {0};
__dfs(root,curSum);
return root;
}
public static void __dfs(TreeNode root,int[] curSum){
// 递归的看右子树
if(root.right!=null)
__dfs(root.right,curSum);
// 处理当前值
root.val += curSum[0];
curSum[0] = root.val;
// 递归的看左子树
if(root.left!=null)
__dfs(root.left,curSum);
}
方法2时间和空间都有大幅提升