Skip to content

Commit e8e6918

Browse files
committed
Solution as on 27-02-2022 08:18 am
1 parent e009e70 commit e8e6918

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// 662.✅ Maximum Width of Binary Tree
2+
3+
class Solution
4+
{
5+
public:
6+
int widthOfBinaryTree(TreeNode *root)
7+
{
8+
if (root == NULL)
9+
return 0;
10+
11+
int res = 1;
12+
queue<pair<TreeNode *, int>> q;
13+
14+
// I am using intialising list
15+
q.push({root, 0}); // also can use make_pair
16+
17+
while (!q.empty())
18+
{
19+
int cnt = q.size();
20+
// start is the index of root node for first level
21+
int start = q.front().second;
22+
int end = q.back().second;
23+
24+
res = max(res, end - start + 1);
25+
26+
for (int i = 0; i < cnt; ++i)
27+
{
28+
pair<TreeNode *, int> p = q.front();
29+
// we will use it while inserting it children
30+
// left child will be 2 * idx + 1;
31+
// right chils will be 2 * idx + 2;
32+
int idx = p.second - start;
33+
34+
q.pop();
35+
36+
// if left child exist
37+
if (p.first->left != NULL)
38+
q.push({p.first->left, (long long)2 * idx + 1});
39+
40+
// if right child exist
41+
if (p.first->right != NULL)
42+
q.push({p.first->right, (long long)2 * idx + 2});
43+
}
44+
}
45+
46+
return res;
47+
}
48+
};

0 commit comments

Comments
 (0)