一. 基础面试题
1. 检查两颗树是否相同
public static boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null){
return true;
}
if(p == null || q == null){
return false;
}
if(q.val != p.val){
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
2. 求另一颗树的子树
public static boolean isSubtree(TreeNode s, TreeNode t) {
if(s == null){
return false;
}
boolean ret = isSameTree(s, t);
if(ret){
return ret;
}
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
3. 判断一颗二叉树是否是平衡二叉树
public static boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
if(root.left == null &&root.right == null){
return true;
}
int rightHeigh = getHeigh(root.right);
int leftHeigh = getHeigh(root.left);
if(leftHeigh - rightHeigh > 1 || leftHeigh - rightHeigh < -1){
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
public static int getHeigh(TreeNode root){
if(root == null){
return 0;
}
int right = getHeigh(root.right);
int left = getHeigh(root.left);
return 1 + (Math.max(right, left));
}
4. 对称二叉树
if(root == null){
return true;
}
return isMirror(root.left, root.right);
}
public static boolean isMirror(TreeNode p, TreeNode q){
if(p == null && q == null){
return true;
}
if(p == null || q == null){
return false;
}
if(p