-
Notifications
You must be signed in to change notification settings - Fork 1
/
MaxWidth.cpp
30 lines (30 loc) · 1016 Bytes
/
MaxWidth.cpp
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
#include<TreeNode.cpp>
using namespace std;
int widthOfBinaryTree(Node* root) {
if (!root)
return 0;
int ans = 0;
queue<pair<Node*, int>> q;
q.push({root, 0});
while (!q.empty()) {
int size = q.size();
int curMin = q.front().second;
int leftMost, rightMost;
for (int i = 0; i < size; i++) {
int cur_id = q.front().second -
curMin; // subtracted to prevent integer overflow
Node* temp = q.front().first;
q.pop();
if (i == 0)
leftMost = cur_id;
if (i == size - 1)
rightMost = cur_id;
if (temp->left)
q.push({temp->left, cur_id * 2 + 1});
if (temp->right)
q.push({temp->right, cur_id * 2 + 2});
}
ans = max(ans, rightMost - leftMost + 1);
}
return ans;
}