判断一棵树是否为搜索二叉树(左子树的值都小于右子树的值)
```bash
```bash
//判断一棵树是否为搜索二叉树
public static int preValue=Integer.MIN_VALUE;
public static boolean checkBST1(TreeNode root){
if (root==null){
return true;
}
boolean isLeftBst = checkBST1(root.left);
if (!isLeftBst){
return false;
}
if (root.val<=preValue){
return false;
}
else {
preValue=root.val;
}
return checkBST1(root.right);
}
public static boolean checkBST2(TreeNode root){
List<TreeNode> list = new ArrayList<>();
process2(root,list);
boolean flag=true;
// TreeNode treeNode = list.get(0);
// System.out.println(treeNode.val);
for (int i = 0; i < list.size()-2; i++) {
if (list.get(i).val>list.get(i+1).val){
return false;
}
}
return flag;
}
public static void process2(TreeNode root,List<TreeNode> inOrderList){
if (root==null){
return;
}
process2(root.left,inOrderList);
inOrderList.add(root);
process2(root.right,inOrderList);
}
判断是否为完全二叉树
判断一棵树是否为满二叉树
判断是否为平衡二叉树:
//判断是否为平衡二叉树
public static boolean isBalanced(TreeNode root){
ReturnType process = process(root);
return process.isBalanced;
}
//定义返回值类型
static class ReturnType{
public boolean isBalanced;
public int height;
public ReturnType(boolean isB,int hei){
isBalanced=isB;
height=hei;
}
}
public static ReturnType process(TreeNode x){
if (x==null){
return new ReturnType(true,0);
}
ReturnType leftData = process(x.left);
ReturnType rightData = process(x.right);
int height=Math.max(leftData.height,rightData.height)+ 1;
Boolean isBalanced = leftData.isBalanced&&rightData.isBalanced&&Math.abs(leftData.height- rightData.height)<2;
return new ReturnType(isBalanced,height);
}
二叉树的递归套路
递归的返回值应该是一样的 结构要一样 所以确定返回三个值
![在这里插入图片描述](https://img-blog.csdnimg.cn/b167862e912d422a952467eb05abf09d.png
// 用递归的套路解决判断是否为搜索二叉树
//首先明确思路 返回值类型 需要判断左子树是否为搜索二叉树 然后还要判断右子树是否为二叉树
// 同时还要满足左子树的最大值要小于右子树的最小值
static class ReturnData{
public boolean isBST;
public int max;
public int min;
public ReturnData(boolean isBST,int max,int min){
this.isBST=isBST;
this.max=max;
this.min=min;
}
}
public static ReturnData process1(TreeNode x){
if (x==null){
// return new ReturnData(true,0,0);
return null;
}
ReturnData leftData = process1(x.left);
ReturnData rightData = process1(x.right);
int min=x.val;
int max=x.val;
if (leftData!=null){
min=Math.max(min,leftData.min);
max= Math.max(max,leftData.max);
}
if (rightData!=null){
min=Math.max(min,rightData.min);
max= Math.max(max,rightData.max);
}
boolean isBST=true;
//左树不为空 同时左边不是搜索二叉树了或者左边的最大值大于x的值
if (leftData!=null&&(!leftData.isBST||leftData.max>=x.val)){
isBST=false;
}
//右树不为空 同时右边不是搜索二叉树了或者右边的最小值小于x的值
if (rightData!=null&&(!rightData.isBST||x.val>= rightData.max)) {
isBST=false;
}
return new ReturnData(isBST,min,max);
//xinde
}
public static boolean checkBST3(TreeNode root){
return process1(root).isBST;
}