From 49860fbc8c25f74be36a0a620ea32542c40f8740 Mon Sep 17 00:00:00 2001 From: Sainik Khaddar <73096052+sainik-khaddar@users.noreply.github.com> Date: Mon, 3 Oct 2022 02:17:56 +0530 Subject: [PATCH] Time: 17 ms (46.16%), Space: 17.4 MB (58.81%) - LeetHub --- .../662-maximum-width-of-binary-tree.cpp | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp diff --git a/662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp b/662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp new file mode 100644 index 0000000..7a1476e --- /dev/null +++ b/662-maximum-width-of-binary-tree/662-maximum-width-of-binary-tree.cpp @@ -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>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;itop=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; + } +}; \ No newline at end of file