轉載自:http://blog.csdn.net/zjwcdd/article/details/51275033
一直在學習這位大牛的部落格,一些算法記錄一下,二叉樹高度不難求,寬度就要花點心思了,這裡轉載一下
以下原文
題目描述:求二叉樹的寬度和深度
給定一個二叉樹,擷取該二叉樹的寬度和深度。
//二叉樹的高度:
public static int getHeight(BiNode head){
if(head == null){
return ;
}
int leftHeight = getHeight(head.left);
int rightHeight = getHeight(head.right);
if(leftHeight > rightHeight){
return leftHeight + ;
}
return rightHeight + ;
}
//二叉樹的寬度:
public static int getWidth(BiNode head){
if(head == null){
return ;
}
Queue<BiNode> queue = new ArrayDeque<BiNode>();
int maxWidth = ;
queue.add(head);
while(true){
int len = queue.size();
if(len == )
break;
while(len > ){
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;
}