Title description
solution:
To judge BST, it is necessary: min<current node<max, and its left and right subtrees also meet similar rules.
To judge a complete binary tree, you need to judge according to the layer, as long as there is one node:
if(cur.left==null && cur.right!=null) return false;
It is not a complete binary tree.
See code:
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;
}
}