Breadth First Search Algorithm to Compute the Max Width of a Binary Tree


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.

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

binary-tree-max-width Breadth First Search Algorithm to Compute the Max Width of a Binary Tree algorithms BFS c / c++ python

Compute the Max Width of Binary Tree using Breadth First Search Algorithm

We can perform the Breadth First Search Algorithm to traverse the binary tree level by level. We also need to record a x-coordinate value which will be multipled by two if we go to left node, and multipled by two and plus one if we go to the right node.

All nodes in the current level are expanded and we compute the min and max coordinate which we then can compute the width.

The following is the C++ implementation of such BFS algorithm, which takes O(N) time and O(N) space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * class Tree {
 *     public:
 *         int val;
 *         Tree *left;
 *         Tree *right;
 * };
 */
int maxWidthBinaryTree(Tree* root) {
    if (!root) return 0;
    int ans = 0;
    queue<pair<Tree*, int>> Q;
    Q.push({root, 0});
    while (!Q.empty()) {
        auto sz = Q.size();
        int left = INT_MAX;
        int right = -INT_MAX + 1;
        for (int i = 0; i < sz; ++ i) {
            auto pt = Q.front();
            Q.pop();
            auto p = pt.first;
            auto v = pt.second;
            left = min(left, v);
            right = max(right, v);
            if (p->left) {
                Q.push({p->left, v * 2});
            }
            if (p->right) {
                Q.push({p->right, v * 2 + 1});
            }            
        }
        ans = max(ans, right - left + 1);
    }
    return ans;
}
/**
 * class Tree {
 *     public:
 *         int val;
 *         Tree *left;
 *         Tree *right;
 * };
 */
int maxWidthBinaryTree(Tree* root) {
    if (!root) return 0;
    int ans = 0;
    queue<pair<Tree*, int>> Q;
    Q.push({root, 0});
    while (!Q.empty()) {
        auto sz = Q.size();
        int left = INT_MAX;
        int right = -INT_MAX + 1;
        for (int i = 0; i < sz; ++ i) {
            auto pt = Q.front();
            Q.pop();
            auto p = pt.first;
            auto v = pt.second;
            left = min(left, v);
            right = max(right, v);
            if (p->left) {
                Q.push({p->left, v * 2});
            }
            if (p->right) {
                Q.push({p->right, v * 2 + 1});
            }            
        }
        ans = max(ans, right - left + 1);
    }
    return ans;
}

Python implementation of BFS algorithm to compute the max width of a binary tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# class Tree:
#     def __init__(self, val, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxWidthBinaryTree(self, root):
        if root is None:
            return 0
        q = [(root, 0)]
        ans = 0
        while len(q) > 0:
            sz = len(q)
            left = float("inf")
            right = float("-inf")
            for i in range(sz):
                p = q.pop(0)
                if p[0].left:
                   q.append((p[0].left, p[1] * 2)) 
                if p[0].right:
                   q.append((p[0].right, p[1] * 2 + 1))
                left = min(left, p[1])
                right = max(right, p[1])
            ans = max(ans, right - left + 1)
        return ans          
# class Tree:
#     def __init__(self, val, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxWidthBinaryTree(self, root):
        if root is None:
            return 0
        q = [(root, 0)]
        ans = 0
        while len(q) > 0:
            sz = len(q)
            left = float("inf")
            right = float("-inf")
            for i in range(sz):
                p = q.pop(0)
                if p[0].left:
                   q.append((p[0].left, p[1] * 2)) 
                if p[0].right:
                   q.append((p[0].right, p[1] * 2 + 1))
                left = min(left, p[1])
                right = max(right, p[1])
            ans = max(ans, right - left + 1)
        return ans          

Compute the Max Width of a Binary Tree:

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
595 words
Last Post: How to Convert Arabic Integers to Roman Numerals?
Next Post: Overclocking ARM CPU of Raspberry PI 4 and 400 with Temperature Cooling Measures

The Permanent URL is: Breadth First Search Algorithm to Compute the Max Width of a Binary Tree

Leave a Reply