zoukankan      html  css  js  c++  java
  • LF.47.Check If Binary Tree Is Completed

    Check if a given binary tree is completed. A complete binary tree is one in which every level of the binary tree 
    is completely filled except possibly the last level. Furthermore, all nodes are as far left as possible. Examples
    5 / 3 8 / 1 4 is completed. 5 / 3 8 / 1 4 11 is not completed. Corner Cases What if the binary tree is null? Return true in this case.
    public class Solution {
      public boolean isCompleted(TreeNode root) {
        // Write your solution here
        if (root == null) {
            return true ;
        }
        Deque<TreeNode> queue = new LinkedList<>();
        /*flag means: 1)the curr root could not have child
        2) the node on the same level as curr could not have child
            5
    
          /    
    
        3        8
    
              /   
    
            1      4
    
        */
        boolean flag = false ;
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode curr = queue.poll() ;
            if (curr.left == null) {
                flag = true ; //左右互斥 要不都没有,要不都有,不能有一个
            } else if (flag) {
                /*
            如果已经标记不能有child(被右边或者之前的node标记-说明气泡)
            但左边不为空 则退出去
                */
                return false ;
            } else{
                queue.offer(curr.left);
            }
            if (curr.right == null) {
                flag = true;
            } else if(flag){
                return false ;
            } else{
                queue.offer(curr.right) ;
            }
        }
        return true ;
      }
    }

    time o(n)--每一个点都要遍历 

    space o(1)

  • 相关阅读:
    比赛F-F Perpetuum Mobile
    HDU 1003(A
    C-C Radar Installation 解题报告
    Codeforces 18C C. Stripe
    HDU 4911 Inversion
    分蛋糕(C
    抄书(B
    深入了解Android蓝牙Bluetooth——《基础篇》
    2W 字详解 Redis 集群环境搭建实践
    漫画 | 阿姨,我不想努力了~
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8684373.html
Copyright © 2011-2022 走看看