转载自:http://blog.csdn.net/zjwcdd/article/details/51275033
一直在学习这位大牛的博客,一些算法记录一下,二叉树高度不难求,宽度就要花点心思了,这里转载一下
以下原文
题目描述:求二叉树的宽度和深度
给定一个二叉树,获取该二叉树的宽度和深度。
public static int getHeight(BiNode head){
if(head == null){
return 0;
}
int leftHeight = getHeight(head.left);
int rightHeight = getHeight(head.right);
if(leftHeight > rightHeight){
return leftHeight + 1;
}
return rightHeight + 1;
}
public static int getWidth(BiNode head){
if(head == null){
return 0;
}
Queue<BiNode> queue = new ArrayDeque<BiNode>();
int maxWidth = 1;
queue.add(head);
while(true){
int len = queue.size();
if(len == 0)
break;
while(len > 0){
BiNode temp = queue.poll();
len--;
if(temp.left != null){
queue.add(temp.left);
}
if(temp.right != null){
queue.add(temp.right);
}
}
maxWidth = Math.max(maxWidth, queue.size());
}
return maxWidth;
}