1. 程式人生 > >LeetCode-Maximum Width of Binary Tree

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