求二叉树的高度与宽度

转载自: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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值