一、算法题
669. 修剪二叉搜索树
class Solution {
public TreeNode trimBST(TreeNode root, int low, int high) {
if(root==null){
return null;
}
if(root.val>high){
//应该递归左子树,并返回左子树符合条件的头结点
return trimBST(root.left,low,high);
}
if(root.val<low){
return trimBST(root.right,low,high);
}
root.left=trimBST(root.left,low,high);
root.right=trimBST(root.right,low,high);
return root;
}
}
- 当root.val>high时,说明此时root的右子树整体都不符合条件不在区间里。因为root.val是root和它右子树中最小的一个值,如果root.val的值都大于右边界了,那么root的右子树整体都会大于右边界,所以直接递归遍历root.left
if(root.val>high){ return trimBST(root.left,low,high); }
- 要遍历完一整棵树,因为可能存在以下的情况
- 0结点不符合条件,如果不遍历完一整棵树就把0结点及其右子树一起删掉的话会不符合题意,应该要继续遍历它的子节点
108.将有序数组转换为二叉搜索树
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
TreeNode root=sort(nums,0,nums.length-1);
return root;
}
public TreeNode sort(int[] nums, int left,int right){
//使用左闭右闭的方式
if(left>right){
return null;
}
//防止越界,int mid=(left+right)/2当left和right都是int最大值时,可能会导致越界
int mid=left+(right-left)/2;
TreeNode cur=new TreeNode(nums[mid]);
cur.left=sort(nums, left, mid-1);
cur.right=sort(nums, mid+1, right);
return cur;
}
}
- 在构造二叉树的时候尽量不要重新定义左右区间数组,而是用下标来操作原数组
- 在每次递归传入下标时,left就传left不要传成0,因为最左端的元素可能先new成节点了,这时候仍需构造成树的数组元素下标最开始就不是0了
538.把二叉搜索树转换为累加树
class Solution {
int sum;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
public void convert(TreeNode root){
if(root==null){
return;
}
//右
convertBST(root.right);
//中
sum+=root.val;
root.val=sum;
//左
convertBST(root.left);
}
}
- 反中序遍历:右中左
- 在中间进行逻辑处理
- sum是用来记录累加值的,每个节点的新值等于sum+该节点的值
二、二叉树总结
-
涉及到二叉树的构造,无论普通二叉树还是二叉搜索树一定前序,都是先构造中节点。
-
求普通二叉树的属性,一般是后序,一般要通过递归函数的返回值做计算。
-
求二叉搜索树的属性,一定是中序了,要不白瞎了有序性了。
文章介绍了如何解决与二叉搜索树相关的三个问题:修剪二叉搜索树、将有序数组转为二叉搜索树和将二叉搜索树转换为累加树。重点强调了构造过程中的前序、中序策略以及在特定场景下的处理方法。

1019

被折叠的 条评论
为什么被折叠?



