zoukankan      html  css  js  c++  java
  • 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.

    How is the binary tree represented?

    We use the level order traversal sequence with a special symbol "#" denoting the null node.

    For Example:

    The sequence [1, 2, 3, #, #, 4] represents the following binary tree:

        1

      /  

     2     3

          /

        4

    /**
     * public class TreeNode {
     *   public int key;
     *   public TreeNode left;
     *   public TreeNode right;
     *   public TreeNode(int key) {
     *     this.key = key;
     *   }
     * }
     */
    public class Solution {
      public boolean isCompleted(TreeNode root) {
        // Write your solution here
        if (root==null){
          return true;
        }
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.offer(root);
        
        int isLeaf = 0;
        while(!q.isEmpty()){
          Queue<TreeNode> nextQ = new LinkedList<TreeNode>();
          int size = q.size();
          for(int i=0; i<size; i++){
            TreeNode curNode = q.poll();
            if(curNode.left==null && curNode.right!=null){
              return false;
            }
            if(curNode.left!=null){
              if(isLeaf==1){
                return false;
              }
              nextQ.offer(curNode.left);
            }
            if(curNode.right!=null){
              if(isLeaf==1){
                return false;
              }
              nextQ.offer(curNode.right);
            }
            if(curNode.left==null || curNode.right==null){
              isLeaf=1;
            }
          }
          q = nextQ;
        }
        return true;
    
      }
    }
  • 相关阅读:
    [堆栈]Linux 中的各种栈:进程栈 线程栈 内核栈 中断栈
    [TI-DSP]sysbios的swi
    [库函数]动态库和静态库优缺点比较
    [S32K]GPIO使用
    [S32K]FreeRTOS使用
    [IC]浅谈嵌入式MCU软件开发之中断优先级与中断嵌套
    [S32K144]多通道ADC使用
    三天搭建博客,包括文章迁移
    网站优化的艺术与科学之实战
    网站优化的艺术与科学之工具和基础知识
  • 原文地址:https://www.cnblogs.com/zg1005/p/12142993.html
Copyright © 2011-2022 走看看