Binary Tree Width - Amazon Top Interview Questions

Problem Statement :

Given a binary tree root, return the maximum width of any level in the tree. The width of a level is the number of nodes that can fit between the leftmost node and the rightmost node.


1 ≤ n ≤ 100,000 where n is the number of nodes in root

Example 1


root = [0, [1, [3, null, null], null], [2, [4, [5, null, null], [6, null, null]], null]]




The maximum width is 3 since between nodes 3 and 4, we can fit total of 3 nodes: [3, null, 4]

Example 2


root = [0, [1, [3, null, null], null], [2, null, [4, null, null]]]




We can fit 4 nodes between 3 and 4.

Example 3


root = [0, null, null]



Solution :


                        Solution in C++ :

int solve(Tree* root) {
    queue<pair<Tree*, int>> q{{{root, 1}}};
    int ans = 1;
    while (!q.empty()) {
        int sz = q.size(), l = INT_MAX, r = INT_MIN;
        while (sz-- > 0) {
            auto& p = q.front();
            l = min(l, p.second), r = max(r, p.second);
            if (p.first->left) q.push({p.first->left, 2 * p.second - 1});
            if (p.first->right) q.push({p.first->right, 2 * p.second});
        ans = max(ans, r - l + 1);
    return ans;

                        Solution in Java :

import java.util.*;

 * public class Tree {
 *   int val;
 *   Tree left;
 *   Tree right;
 * }
class Solution {
    public int solve(Tree root) {
        LinkedList<Pair<Tree, Integer>> q = new LinkedList();
        q.addLast(new Pair(root, 0));
        int res = 0;

        while (q.size() > 0) {
            int size = q.size();
            // compare leftmost and rightmost
            Pair<Tree, Integer> left = q.getFirst();
            Pair<Tree, Integer> right = q.getLast();
            int left_column = left.getValue();
            int right_column = right.getValue();
            res = Math.max(res, right_column - left_column + 1);

            for (int i = 0; i < size; i++) { // standard BFS
                Pair<Tree, Integer> cur = q.removeFirst();
                Tree cur_node = cur.getKey();
                int cur_column = cur.getValue();
                if (cur_node.left != null) {
                    q.addLast(new Pair(cur_node.left, 2 * cur_column));
                if (cur_node.right != null) {
                    q.addLast(new Pair(cur_node.right, 2 * cur_column + 1));
        return res;

                        Solution in Python : 
from typing import Deque

class Solution:
    def solve(self, root):
        max_width = 0
        queue: Deque[list[tuple[Tree, int]]] = deque([(root, 1)]) if root else deque()
        while queue:
            max_width = max(max_width, queue[-1][1] - queue[0][1] + 1)
            length = len(queue)
            for _ in range(length):
                node, index = queue.popleft()
                for child, new_index in ((node.left, 2 * index), (node.right, 2 * index + 1)):
                    if child:
                        queue.append((child, new_index))
        return max_width

View More Similar Problems

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →


This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →