1、判断是否为二叉搜索树【LC 98题】
- 中序遍历的思想去判断。
先判断左子树是否为二叉搜索树,再判断head.val>preValue,最后返回右子树是否为BST
class Solution {
long preValue=Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if(root==null) return true;
if(!isValidBST(root.left)) return false;
if(root.val<=preValue) return false;
else{
preValue=root.val;
return isValidBST(root.right);
}
}
}
犯的错误:把preValue的定义写到方法体内了,这样并没有存储上一个头结点的值。
- 直接生成中序遍历序列
遍历中序列表,判断是否都是递增
public boolean isValidBST(TreeNode root) {
ArrayList<Integer> list=new ArrayList<>();
inOrder(root,list);
for (int i = 0; i < list.size()-1; i++) {
if (list.get(i)>=list.get(i+1)) return false;
}
return true;
}
public void inOrder(TreeNode root,ArrayList<Integer> list){
if (root==null) return;
inOrder(root.left,list);
list.add(root.val);
inOrder(root.right,list);
}
2、判断是否为完全二叉树【LC 958题】
利用层序遍历,判断规则如下:
- 任意节点有右孩子,无左孩子,直接返回false;
- 在条件1满足的情况下,如果节点不是有两个孩子的话【非全节点】,则之后的所有节点必须都是叶子节点。否则返回false
public boolean isCompleteTree(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
boolean leaf=false; //记录有没有遇到过 非全节点
while (!queue.isEmpty()){
TreeNode temp=queue.poll();
TreeNode l=temp.left;
TreeNode r=temp.right;
if (l==null && r!=null) return false;
if (leaf && (l!=null||r!=null)) return false;
if (l==null || r==null) leaf=true;
if (l!=null) queue.add(l);
if (r!=null) queue.add(r);
}
return true;
}
3、判断是否为满二叉树
return 二叉树的节点个数==pow(2,二叉树深度)-1;
public static boolean isfullTree(TreeNode root){
if (root == null) return true;
TreeNode temp=root;
int level=0;
while (temp!=null){
level++;
temp=temp.left;
}
return countNodes(root)==(int)Math.pow(2,level)-1;
}
private static int countNodes(TreeNode root) {
if (root==null) return 0;
return countNodes(root.left)+countNodes(root.right)+1;
}
4、判断是否为平衡二叉树【LC 110题】
- 如果子树不是平衡二叉树,那直接返回-1;
- 在左右子树都是平衡二叉树的前提下,判断左右子树的深度差是否小于等于1,大于则返回-1
- 满足1、2后则返回左右子树中的较大深度+1作为当前节点的深度。
public boolean isBalanced(TreeNode root) {
if (root==null) return true;
return maxDepth(root)!=-1;
}
private int maxDepth(TreeNode root) {
if (root==null) return 0;
int left=maxDepth(root.left);
if (left==-1) return -1;
int right=maxDepth(root.right);
if (right==-1) return -1;
if (Math.abs(left-right)>1) return -1;
return Math.max(left,right)+1;
}