树的宽度

import com.lifeibigdata.algorithms.leetcode.TreeNode;

import java.util.ArrayDeque;
import java.util.Queue;


public class TreeWidth {

    /**
     * 使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。
     * 以此类推,依次遍历下一层即可求出二叉树的最大宽度
     * @param root
     * @return
     */
    static int getTreeWidth(TreeNode  root){
        if (root == null) return 0;
        Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
        int maxWidth = 0;
        queue.add(root);
        while (true){              //
            int len = queue.size();
            if (len == 0) break;
            while (len > 0){      //保证上一层被遍历完毕,所以使用了len变量
                TreeNode t = queue.poll();
                len--;
                if (t.left != null) queue.add(t.left);
                if (t.right != null) queue.add(t.right);
            }
            maxWidth = Math.max(maxWidth,queue.size());
        }
        return maxWidth;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值