求二叉树的深度和宽度

来源:互联网 发布:java多人聊天 编辑:程序博客网 时间:2024/06/05 11:10

题目描述:求二叉树的宽度和深度
给定一个二叉树,获取该二叉树的宽度和深度。

    //二叉树的高度:    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;    }
0 0
原创粉丝点击