LeetCode-Maximum Width of Binary Tree

一、Description

题目描述:给定一个二叉树,返回它的最大宽度。最大宽度是这么定义的:即一层中最右结点与最左结点之间的长度。

Example 1:

Input: 

           1
         /   \
        3     2
       / \     \  
      5   3     9 

Output: 4
Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).

Example 2:

Input: 

          1
         /  
        3    
       / \       
      5   3     

Output: 2
Explanation: The maximum width existing in the third level with the length 2 (5,3).

Example 3:

Input: 

          1
         / \
        3   2 
       /        
      5      

Output: 2
Explanation: The maximum width existing in the second level with the length 2 (3,2).

Example 4:

Input: 

          1
         / \
        3   2
       /     \  
      5       9 
     /         \
    6           7
Output: 8
Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).

二、Analyzation

可通过层次遍历即BFS来求解。对于每一层的第一个结点,记下它对应的下标,对于每一层的最后一个结点,判断它与第一个结点之间的长度是否大于max,最后得到的max必然是最大的宽度。


三、Accepted code

class Solution {
    public int widthOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        Map<TreeNode, Integer> map = new HashMap<>();
        map.put(root, 1);
        int max = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            int left = 0;
            for (int i = 0; i < size; i++) {
                TreeNode temp = queue.poll();
                int index = map.get(temp);
                if (i == 0) {
                    left = index;
                }
                if (i == size - 1) {
                    max = Math.max(max, index - left + 1);
                }
                if (temp.left != null) {
                    map.put(temp.left, 2 * index + 1);
                    queue.add(temp.left);
                }
                if (temp.right != null) {
                    map.put(temp.right, 2 * index + 2);
                    queue.add(temp.right);
                }
            }
        }
        return max;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值