LeetCode-Maximum Width of Binary Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83684061

一、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;
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83684061
今日推荐