一、题目内容

image.png

二、题解

解法1:

思路

分别判断

  • 完全二叉树
    • 层序遍历,null值也入队
    • 最终层序遍历的结果,队列中不会有null间隔
  • 搜索二叉树

    • 左右递归
    • root为左子树的最大值,右子树的最小值
    • isSearch(root.left,min,root.val) && isSearch(root.right,root.val,max);

      代码

      1. public class Solution {
      2. /**
      3. *
      4. * @param root TreeNode类 the root
      5. * @return bool布尔型一维数组
      6. */
      7. public boolean[] judgeIt (TreeNode root) {
      8. // write code here
      9. return new boolean[]{isSearch(root,null,null),isAllTree(root)};
      10. }
      11. private boolean isSearch(TreeNode root,Integer min,Integer max){
      12. if(root == null){
      13. return true;
      14. }
      15. // 如果root值小于最低项则不是搜索二叉树
      16. if(min!=null && root.val<=min){
      17. return false;
      18. }
      19. if(max!=null && root.val>=max){
      20. return false;
      21. }
      22. return isSearch(root.left,min,root.val) && isSearch(root.right,root.val,max);
      23. }
      24. private boolean isAllTree(TreeNode root){
      25. if(root == null) {
      26. return true;
      27. }
      28. Queue<TreeNode> queue = new LinkedList<TreeNode>();
      29. queue.offer(root);
      30. TreeNode left = null, right = null;
      31. while(!queue.isEmpty()){
      32. TreeNode node = queue.poll();
      33. if(node!=null){
      34. queue.offer(node.left);
      35. queue.offer(node.right);
      36. }else{
      37. while(!queue.isEmpty()){
      38. if(queue.poll()!=null){
      39. return false;
      40. }
      41. }
      42. }
      43. }
      44. return true;
      45. }
      46. }