zoukankan      html  css  js  c++  java
  • 二叉树——判断一棵树是否是完全二叉树

    二叉树按层遍历

    判断条件:结点的左右孩子只有4种情况

    其中的三种情况有特例

    条件1.结点有右孩子,没有左孩子,直接返回false

    条件2.结点左右孩子不全(有左没右,左右都没有),则后面遇到的所有结点,都必须是叶节点

    只要不违反1.2的,就是完全二叉树

    public class IsCBTTree {
        public static boolean isCBTTree(Tree tree){
            if(tree == null) return true;
    
            //是否开启叶子结点,之后如果遇到不是叶子结点时,就不是完全二叉树
            boolean isLeaf = false;
    
            Queue<Tree> queue = new LinkedList<>();
            queue.offer(tree);
            while(!queue.isEmpty()){
                tree = queue.poll();
                Tree l = tree.left;
                Tree r = tree.right;
                if((l == null && r != null) || (isLeaf && (l != null || r != null))){
                    return false;
                }
    
                if(l != null){
                    queue.offer( l );
                }
    
                if(r != null){
                    queue.offer( r );
                }
    
                if(l == null || r == null){
                    isLeaf = true;
                }
            }
            return true;
        }
    }
    

      

  • 相关阅读:
    集合set
    字典
    元组
    列表
    for循环
    Windows调试2.异常产生详细流程
    双机环境搭建
    Windows调试1.WinDbg基本使用-异常基础知识
    PE基础7-HOOK练习
    PE基础6_远程线程注入-HOOK(消息-InLine-IAT)
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8947531.html
Copyright © 2011-2022 走看看