题解 | #判断一棵二叉树是否为搜索二叉树和完全二叉树#
判断一棵二叉树是否为搜索二叉树和完全二叉树
http://www.nowcoder.com/practice/f31fc6d3caf24e7f8b4deb5cd9b5fa97
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类 the root
* @return bool布尔型一维数组
*/
// 存放中序遍历结果
ArrayList<Integer> zhongList = new ArrayList<>();
public boolean[] judgeIt (TreeNode root) {
// write code here
zhongxu(root);
boolean[] returnArray = new boolean[2];
returnArray[0] = judgeUper();
returnArray[1] = judgeWanQuan(root);
return returnArray;
}
// 中序遍历二叉树
public void zhongxu(TreeNode root){
if(root != null){
zhongxu(root.left);
zhongList.add(root.val);
zhongxu(root.right);
}
}
// 判断是不是升序
public boolean judgeUper(){
for(int i = 0; i < zhongList.size()-1; i++){
if(zhongList.get(i) > zhongList.get(i+1)){
return false;
}
}
return true;
}
// 层次遍历二叉树判断是不是完全二叉树
public boolean judgeWanQuan(TreeNode root){
// 定义一个队列
LinkedList<TreeNode> duiLie = new LinkedList<>();
duiLie.add(root);
TreeNode del = null;
while(duiLie.peek() != null){
del = duiLie.poll();
duiLie.add(del.left);
duiLie.add(del.right);
}
while(!duiLie.isEmpty() && duiLie.peek() == null){
duiLie.poll();
}
return duiLie.isEmpty();
}
}