题目描述
解法:
判断BST的话需要:min<当前节点<max,同时其左右子树也满足相似的规则。
判断完全二叉树,则需要按照层去判断,只要有一个节点存在:
if(cur.left==null && cur.right!=null) return false;
则不是完全二叉树。
见代码:
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类 the root
* @return bool布尔型一维数组
*/
public boolean[] judgeIt (TreeNode root) {
// write code here
boolean[]res = new boolean[2];
if(root==null) {
res[0] = true;
res[1] = true;
return res;
}
res[0] = isBST(root,Integer.MAX_VALUE,Integer.MIN_VALUE);
res[1] = isBinaryTree(root);
return res;
}
//判断BST二叉树,使用一个max和min来限制范围:
//当前节点必须满足: max>=root>=min
public boolean isBST(TreeNode root,int max,int min){
if(root== null) return true;
if(root.val>=max || root.val<=min){
return false;
}
boolean leftRes = isBST(root.left,root.val,min);
boolean rightRes = isBST(root.right,max,root.val);
return leftRes && rightRes;
}
public boolean isBinaryTree(TreeNode root){
if(root==null) return true;
//完全二叉树的标号同满二叉树的标号则相同。
//按照层级遍历的序号,如果得到的数据和满二叉树的节点值一致则为true
int fullId = 0;//满二叉树的id
int judgeId = 0;//完全二叉树的id
LinkedList<TreeNode> que = new LinkedList<>();
que.add(root);
while(!que.isEmpty()){
int size = que.size();
for(int i=0;i<size;i++){//当前层的节点
TreeNode cur = que.remove();
if(cur!=null){
if(cur.left==null && cur.right!=null) return false;
que.add(cur.left);
que.add(cur.right);
}else continue;
}
}
return true;
}
}