树宽高

来源:互联网 发布:淘宝无线网址怎么转换 编辑:程序博客网 时间:2024/06/06 00:16
import java.util.Queue;import java.util.LinkedList;public final class Demo {public static class BiNode {public char data;public BiNode left;public BiNode right;public BiNode(char data) {this.data = data;}}public static class BiNodeInfo {public int width = 0;public int height = 0;}/* * Description 给定一个二叉树,获取该二叉树的宽度深度。 * Input Param: head  需要获取深度的二叉树头结点  * Return Value: width 宽度 height 高度  */public static BiNodeInfo getBiNodeInfo(BiNode head) {/* 在这里实现功能 */if(head==null){return new BiNodeInfo();}Queue<BiNode> queue=new LinkedList<BiNode>();queue.offer(head);int height=0;int width=0;int len=1;while(!queue.isEmpty()){height++;width=Math.max(width, len);int tlen=0;for(int i=0;i<len;i++){BiNode node=queue.poll();if(node.left!=null){queue.offer(node.left);tlen++;}if(node.right!=null){queue.offer(node.right);tlen++;}}len=tlen;}BiNodeInfo bi=new BiNodeInfo();bi.width=width;bi.height=height;return bi;}}

0 0
原创粉丝点击