🚩传送门:牛客题目

题目

给定一棵二叉树,已知其中的节点没有重复值,请判断该二叉树是否为搜索二叉树和完全二叉树。
输出描述:分别输出是否为搜索二叉树、完全二叉树。
注意:空子树我们认为同时符合搜索二叉树和完全二叉树。

示例2

输入:{1,#,2} 返回值:{true,false} 说明:由于节点的右儿子大于根节点,无左子树,所以是搜索二叉树但不是完全二叉树

解题思路:递归+层次遍历

  1. 递归判断是否是搜索二叉树
  2. 利用层次遍历判断是否是完全二叉树

复杂度分析

时间复杂度:[NC]60. 判断一棵二叉树是否为搜索二叉树和完全二叉树 - 图1[NC]60. 判断一棵二叉树是否为搜索二叉树和完全二叉树 - 图2 为二叉树的节点个数。

  1. - 二叉树的每个节点被访问两次,因此时间复杂度为 ![](https://cdn.nlark.com/yuque/__latex/7ba55e7c64a9405a0b39a1107e90ca94.svg#card=math&code=O%28n%29&height=23&id=X3zRr)

空间复杂度:[NC]60. 判断一棵二叉树是否为搜索二叉树和完全二叉树 - 图3[NC]60. 判断一棵二叉树是否为搜索二叉树和完全二叉树 - 图4 为二叉树的节点个数。

  1. - 队列最多存储 ![](https://cdn.nlark.com/yuque/__latex/ea02f5f09fa635e33c4857ec99404ad9.svg#card=math&code=2n-1&height=23&id=tURpv) 个节点,因此需要额外的 ![](https://cdn.nlark.com/yuque/__latex/7ba55e7c64a9405a0b39a1107e90ca94.svg#card=math&code=O%28n%29&height=23&id=ncJyW) 的空间。

我的代码

  1. public class Solution {
  2. public boolean isSerachTreeBST(TreeNode root,int low,int hight){
  3. if(root==null)
  4. return true;
  5. if(root.val>hight||root.val<low)
  6. return false;
  7. return isSerachTreeBST(root.left,low,root.val)
  8. && isSerachTreeBST(root.right,root.val,hight);
  9. }
  10. public boolean isAllTreeBST(TreeNode root){
  11. if(root==null)return true;
  12. LinkedList<TreeNode> q=new LinkedList<>();
  13. q.addLast(root);
  14. //当左右子树中出现一个空缺,说明后面不能再有结点
  15. while(q.peek()!=null){
  16. TreeNode node=q.poll();
  17. q.addLast(node.left);
  18. q.addLast(node.right);
  19. }
  20. while (!q.isEmpty()&&q.peek()==null)
  21. q.poll();
  22. return q.isEmpty();
  23. }
  24. public boolean[] judgeIt (TreeNode root) {
  25. // write code here
  26. boolean[]ans=new boolean[]{true,true};
  27. if(root==null)return ans;
  28. ans[0]=isSerachTreeBST(root,Integer.MIN_VALUE,Integer.MAX_VALUE);
  29. ans[1]=isAllTreeBST(root);
  30. return ans;
  31. }
  32. }