求二叉树的宽度
2016-03-14 09:31
337 查看
题目描述
给出一棵二叉树,求二叉树的宽度。
解析
二叉树的宽度:空的二叉树的宽度为0,非空二叉树的宽度为各层结点个数的最大值。
依然用BFS。
给出一棵二叉树,求二叉树的宽度。
解析
二叉树的宽度:空的二叉树的宽度为0,非空二叉树的宽度为各层结点个数的最大值。
依然用BFS。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if (root==null) { return 0; } Queue<TreeNode> que=new ArrayDeque<TreeNode>(); int MaxWidth=1;//最大宽度 que.add(root); while(true){ int count=que.size();//que.size()表示队列中的元素 if (count==0) { break; } while (count>0) {//将上一层中所有结点清空,并加入下一层所有结点 TreeNode temp=que.poll();//取出队首元素 count--; if (temp.left!=null) { que.add(temp.left); } if (temp.right!=null) { que.add(temp.right); } } MaxWidth=Math.max(MaxWidth, que.size());// } return MaxWidth; } }
相关文章推荐
- 如何修改主库的数据文件并将改变传导至备库 mos文章 (文档 ID 733796.1)
- Bootstrap的JavaScript插件实现步骤
- 源文件与模块生成时的文件不同,是否希望调试器使用它?如何解决
- asp.net 内置对象
- Android程序开发之自定义设置TabHost,TabWidget样式
- 10012---SpringMVC视图解析流程
- 脚本语言和编程语言的区别
- [LeetCode]26. Remove Duplicates from Sorted Array
- WPF-基础知识介绍
- 重整晋商雄风,再现汇通天下 -------《晋商》阅读笔记第7-9章
- java 读取文件的创建 时间和修改时间
- android 记录崩溃日志
- listview使用小技巧
- ClassLoader详解及用途
- java-堆栈与队列之间的转换
- 读《Introducing Go》O'Reilly,第3,4章
- 详解设计模式中的Command命令模式及相关C++实现
- 《iOS Human Interface Guidelines》——Page View Controller
- linux 创建用户和组
- 深入理解Java(一)类加载原理