662. Maximum Width of Binary Tree

Problem:
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.
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).


Note: Answer will in the range of 32-bit signed integer.

Analysis:
BFS, better to calc width at current level instead of next level. 

Solution:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
 public int widthOfBinaryTree(TreeNode root) {
        Queue<Pair> queue = new LinkedList<>();
        queue.offer(new Pair(root, 1));
        int res = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            int left = queue.peek().pos, right = left;
            for (int i = 0; i < size; i++) {
                Pair cur = queue.poll();
                right = cur.pos;
                if (cur.node.left != null) {
                    int pos = cur.pos * 2;
                    queue.offer(new Pair(cur.node.left, pos));
                }
                if (cur.node.right != null) {
                    int pos = cur.pos *2 +1;
                    queue.offer(new Pair(cur.node.right, pos));
                }
            }
            res = Math.max(res, right - left + 1);
        }
        return  res;
    }

    class Pair {
        TreeNode node;
        int pos;

        public Pair(TreeNode node, int pos) {
            this.node = node;
            this.pos = pos;
        }
    }
}

评论

此博客中的热门博文

776. Split BST

663. Equal Tree Partition

532. K-diff Pairs in an Array