forked from Mohammed-Shoaib/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC0662.cpp
More file actions
executable file
·37 lines (32 loc) · 719 Bytes
/
LC0662.cpp
File metadata and controls
executable file
·37 lines (32 loc) · 719 Bytes
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
36
37
/*
Problem Statement: https://leetcode.com/problems/maximum-width-of-binary-tree/
Time: O(n)
Space: O(n)
Author: Mohammed Shoaib, github.com/Mohammed-Shoaib
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
int max_w = 0;
queue<pair<TreeNode*, int>> q;
if (root)
q.push({root, 0});
while (!q.empty()) {
int size, beg, end, idx;
size = q.size();
beg = q.front().second;
end = q.back().second;
max_w = max(end - beg + 1, max_w);
while (size--) {
tie(root, idx) = q.front();
q.pop();
idx -= beg;
if (root->left)
q.push({root->left, 2 * idx + 1});
if (root->right)
q.push({root->right, 2 * idx + 2});
}
}
return max_w;
}
};