leetcode669. 修剪二叉搜索树
注意:×
- 刚开始想不通为什么啥操作都没有,直接return就好了,仔细思考一下,其实null的操作就是把这个分支给去除掉了
public TreeNode trimBST(TreeNode root, int low, int high) {
if (root == null) {
return null;
}
if (root.val < low){
return trimBST(root.right, low, high);
}
if (root.val > high){
return trimBST(root.left, low, high);
}
root.left = trimBST(root.left, low, high);
root.right = trimBST(root.right, low, high);
return root;
}
leetcode108.将有序数组转换为二叉搜索树
注意:√
- 一遍过,感觉和之前的数组构建二叉树很像,Labuladong书里面肯定有,不记得随想录里面有没有这个
public TreeNode sortedArrayToBST(int[] nums) {
if (nums.length == 0){
return null;
}
return build(nums, 0, nums.length-1);
}
private TreeNode build(int[] nums, int lo, int hi) {
if (lo>hi){
return null;
}
int index = lo+(hi-lo)/2;
TreeNode root = new TreeNode(nums[index]);
root.left = build(nums, lo, index-1);
root.right = build(nums, index+1, hi);
return root;
}
leetcode538. 把二叉搜索树转换为累加树
注意:√
- 之前看过Labuladong书中内容,先右后左的遍历顺序+外部sum解决
int sum = 0;
public TreeNode convertBST(TreeNode root) {
traverse(root);
return root;
}
private void traverse(TreeNode root) {
if (root == null){
return;
}
traverse(root.right);
sum = sum+root.val;
root.val = sum;
traverse(root.left);
return;
}