BST考察中序遍历,完全二叉树考察层次遍历第一个空节点之后节点的情况
判断一棵二叉树是否为搜索二叉树和完全二叉树
http://www.nowcoder.com/questionTerminal/f31fc6d3caf24e7f8b4deb5cd9b5fa97
BST中序遍历有有序的,这是充要条件。---保存前一个节点:成员变量pre
private TreeNode pre;
public boolean isBst(TreeNode root){
if(root==null){
return true;
}
if(!isBst(root.left)){
return false;
}
if(pre!=null&&pre.val>=root.val){
return false;
}
//保存前一个节点
pre=root;
if(!isBst(root.right)){
return false;
}
return true;
} 完全二叉树,层次遍历遇到第一个空节点后,剩余节点还有非空,则一定不是.巧用continue并配合标志位。
/**
* 验证是否为完全二叉树
* @param root 树
* @return 验证是否为完全二叉树
*/
public boolean isCompleteTree(TreeNode root) {
if(root==null){
return true;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
TreeNode cur;
boolean notComplete=false;
while (!queue.isEmpty()){
cur=queue.remove();
if(cur==null){
notComplete=true;
//第一个空节点之后的节点,countinue使用的很妙
continue;
}
if(notComplete){
return false;
}
queue.add(cur.left);
queue.add(cur.right);
}
return true;
}
最后答案依次调用以上两个函数OK。注意返回数组时前面有new boolean[]
public boolean[] judgeIt (TreeNode root) {
return new boolean[]{isBst(root), isCompleteTree(root)};
}
阿里巴巴灵犀互娱公司福利 650人发布

查看18道真题和解析