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

    给你一颗二叉树,判断是否是完全二叉树?

    思路:BFS+ 层序遍历。二叉树的每一个节点,如果其子节点为空,则视为空。若为完全二叉树,则最后的空都在最后;若非完全二叉树,则在空之后还会有其他

    元素,实现的时候借助于判断队列是否为空,循环取出元素,判断该元素是否为null即可。

    bug卡在了java的队列接口,入队列是add, 出队列是poll .而不是 push和pop。

    核心代码:

     1     public  static boolean isCompleteTree(TreeNode root) {
     2         if(root==null){
     3             return false;
     4         }
     5 
     6         Queue<TreeNode> queue = new LinkedList<TreeNode>();
     7         ((LinkedList<TreeNode>) queue).push(root);
     8 
     9         TreeNode cur;
    10 
    11         while ( ( cur = ((LinkedList<TreeNode>) queue).poll()) != null){
    12             ((LinkedList<TreeNode>) queue).add(cur.left);
    13             ((LinkedList<TreeNode>) queue).add(cur.right);
    14         }
    15 
    16 
    17         while (!queue.isEmpty()){
    18             cur = ((LinkedList<TreeNode>) queue).poll();
    19             if(cur!=null){
    20                 return false;
    21             }
    22         }
    23 
    24         return true;
    25     }
  • 相关阅读:
    springmvc的注解式开发
    springmvc
    spring整合Mybatis
    spring的事务管理
    注解定义增强的两个方法
    动态代理
    错题解析
    SpringMVC的基本操作
    Spring整合MyBatis
    配置事务以及事务回滚
  • 原文地址:https://www.cnblogs.com/vector11248/p/10126070.html
Copyright © 2011-2022 走看看