LintCode 1101. 二叉树最大宽度

题目描述

给定一颗二叉树, 编写一个函数求该树的最大宽度, 即该树每一层的宽度的最大值. 该二叉树具有与满二叉树相同的结构, 但是一些节点为空 null.

二叉树某一层的宽度定义为该层两端节点之间的距离. 注意, 两端节点之间的空节点也算作长度.

样例

样例1:
输入: 
           1
         /   \
        3     2
       / \     \  
      5   3     9 
输出: 4
解释: 第三层的最大宽度为4:(5,3,#,9)。

样例2:
输入: 
          1
         /  
        3    
       / \       
      5   3     	
输出: 2
解释: 最大长度在第三层,长度为2: (5,3)。

样例3:	
输入: 	
          1
         / \
        3   2 
       /        
      5      
输出: 2
解释: 最大长度在第二层,长度为2:(3,2).

样例4:
输入: 
          1
         / \
        3   2
       /     \  
      5       9 
     /         \
    6           7			
输出: 8
解释: 最大长度在第四层,长度为8: (6,#,#,#,#,#,#,7).

分析:

左儿子下标是2*n,右儿子下标是2*n+1,BFS和DFS都可以,代码采用BFS。

JAVA代码:

public int widthOfBinaryTree(TreeNode root) {
    if (root == null)
        return 0;
    Queue<TreeNode> nodes = new LinkedList<>();
    Queue<Integer> counts = new LinkedList<>();
    ((LinkedList<TreeNode>) nodes).add(root);
    ((LinkedList<Integer>) counts).add(1);
    int size, temp;
    int min , max , res = 0;
    TreeNode tree;
    while (!nodes.isEmpty()) {
        min = Integer.MAX_VALUE;
        max = Integer.MIN_VALUE;
        size = nodes.size();
        while (size != 0) {
            tree = nodes.poll();
            temp = counts.poll();
            min = Math.min(temp, min);
            max = Math.max(temp, max);
            if (tree.left != null) {
                ((LinkedList<TreeNode>) nodes).add(tree.left);
                ((LinkedList<Integer>) counts).add(temp * 2);
            }
            if (tree.right != null) {
                ((LinkedList<TreeNode>) nodes).add(tree.right);
                ((LinkedList<Integer>) counts).add(temp * 2 + 1);
            }
            size--;
        }
        res = Math.max(max - min + 1, res);
    }
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值