您的位置:首页 > 其它

求二叉树的宽度

2016-03-14 09:31 337 查看
题目描述

给出一棵二叉树,求二叉树的宽度。

解析

二叉树的宽度:空的二叉树的宽度为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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: