判断一棵树是否是完全二叉树

根据完全二叉树的定义,如果二叉树上某个结点有右孩子无左孩子则一定不是完全二叉树;否则如果二叉树上某个结点有左孩子而没有右孩子,那么该结点所在的那一层上,该结点右侧的所有结点应该是叶子结点,否则不是完全二叉树。

import java.util.LinkedList; import java.util.Queue; public class tmp { public static class Node{ //一个静态内部类 int data; Node left; Node right; public Node(int data) { this.data = data; } } public static boolean isCompleteBtree(Node root) { if(root == null) { return true; } Queue<Node> queue = new LinkedList<Node>(); queue.offer(root); boolean leaf = false; while(!queue.isEmpty()) { Node node = queue.poll(); //左空右不空 if(node.left == null && node.right != null) { return false; } //如果开启了叶子结点阶段,结点不能有左右孩子 if(leaf && (node.left != null || node.right != null)) { return false; } //将下一层要遍历的加入到队列中 if(node.left != null) { queue.offer(node.left); } if(node.right != null) { queue.offer(node.right); } else { leaf = true; } } return true; } public static void main(String[] args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.right = new Node(4); System.out.println(isCompleteBtree(root)); } }

__EOF__

本文作者程序员小宇
本文链接https://www.cnblogs.com/treasury/p/13258462.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   程序员小宇  阅读(704)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示