-
Notifications
You must be signed in to change notification settings - Fork 56
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 17 ms (46.16%), Space: 17.4 MB (58.81%) - LeetHub
- Loading branch information
1 parent
04b6991
commit 49860fb
Showing
1 changed file
with
39 additions
and
0 deletions.
There are no files selected for viewing
39 changes: 39 additions & 0 deletions
39
662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
/** | ||
* 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) | ||
return 0; | ||
int res=1; | ||
queue<pair<TreeNode*,int>>q; | ||
q.push({root,0}); | ||
while(!q.empty()) | ||
{ | ||
int n=q.size(); | ||
int left=q.front().second; | ||
int right=q.back().second; | ||
res=max(res,right-left+1); | ||
for(int i=0;i<n;i++) | ||
{ | ||
pair<TreeNode*,int>top=q.front(); | ||
q.pop(); | ||
int idx=top.second-left; | ||
if(top.first->left) | ||
q.push({top.first->left,(long long)2*idx+1}); | ||
if(top.first->right) | ||
q.push({top.first->right,(long long)2*idx+2}); | ||
} | ||
} | ||
return res; | ||
} | ||
}; |