求二叉树的宽度,就是求二叉树某一层上的节点数最多的数。
public static int getHeight(BiNode head)
{
int deep = 0;
if(head != null)
{
int left = getHeight(head.left);
int right = getHeight(head.right);
deep = (left>=right)?(left+1):(right+1);
}
return deep;
}
public static int getWidth(BiNode head)
{
if(head == null)
{
return 0;
}
int nWidth = 0;
int nLastLevelWidth = 0;
int nTempLastLevelWidth = 0;
int nCurLevelWidth = 0;
Queue<BiNode> myQueue = new LinkedList<Demo.BiNode>();
myQueue.add(head);
nLastLevelWidth = 1;
nWidth = 1;
while(!myQueue.isEmpty())
{
nTempLastLevelWidth = nLastLevelWidth;
BiNode tmp = null;
while(nTempLastLevelWidth != 0)
{
tmp = myQueue.peek();
myQueue.poll();
if(tmp.left != null)
{
myQueue.add(tmp.left);
}
if(tmp.right != null)
{
myQueue.add(tmp.right);
}
nTempLastLevelWidth--;
}
nCurLevelWidth = myQueue.size();
nWidth = nCurLevelWidth>nWidth?nCurLevelWidth:nWidth;
nLastLevelWidth = nCurLevelWidth;
}
return nWidth;
}
参考:http://zhidao.baidu.com/link?url=K1xVilT0OyF_e_FbYr9FVycdq4MBgacNU-1iCOWtGvFJqwb28q1e5j1EJ4QefSy6Qe15ZHD9qV10Bi439AWbuq
http://zhidao.baidu.com/link?url=K1xVilT0OyF_e_FbYr9FVycdq4MBgacNU-1iCOWtGvFJqwb28q1e5j1EJ4QefSy6Qe15ZHD9qV10Bi439AWbuq