-
Notifications
You must be signed in to change notification settings - Fork 733
/
Copy pathMaximum Width of a binary tree
66 lines (54 loc) · 1.87 KB
/
Maximum 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Maximum Width of Binary Tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int widthOfBinaryTree(TreeNode* root) {
if (root==NULL)
return 0;
int ans =0;
queue<pair<TreeNode*,int>>q;
q.push(make_pair(root,0));
//start level order traversal
while(!q.empty())
{
int size=q.size();
int minindex,first,last;
minindex=q.front().second;
for(int i=0;i<size;i++)
{
pair<TreeNode* , int>temp=q.front();
TreeNode*curr=temp.first;
//making index valid to avoid overflow
int currindex=temp.second-minindex;
q.pop();
//findind first and last index
if(i==0)
first=temp.second-minindex;
if(i==size-1)
last=temp.second-minindex;
//now push in the queue the left and right child
if(curr->left)
q.push(make_pair(curr->left, (long long)currindex*2 +1));
if(curr->right)
q.push(make_pair(curr->right, (long long)currindex*2 +2));
}
ans= max(ans,last-first +1);
}
return ans;
}
};
/*
Output
Input: root = [1,3,2,5,3,null,9]
Output: 4
Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).