File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ // 662.✅ Maximum Width of Binary Tree
2+
3+ class Solution
4+ {
5+ public:
6+ int widthOfBinaryTree (TreeNode *root)
7+ {
8+ if (root == NULL )
9+ return 0 ;
10+
11+ int res = 1 ;
12+ queue<pair<TreeNode *, int >> q;
13+
14+ // I am using intialising list
15+ q.push ({root, 0 }); // also can use make_pair
16+
17+ while (!q.empty ())
18+ {
19+ int cnt = q.size ();
20+ // start is the index of root node for first level
21+ int start = q.front ().second ;
22+ int end = q.back ().second ;
23+
24+ res = max (res, end - start + 1 );
25+
26+ for (int i = 0 ; i < cnt; ++i)
27+ {
28+ pair<TreeNode *, int > p = q.front ();
29+ // we will use it while inserting it children
30+ // left child will be 2 * idx + 1;
31+ // right chils will be 2 * idx + 2;
32+ int idx = p.second - start;
33+
34+ q.pop ();
35+
36+ // if left child exist
37+ if (p.first ->left != NULL )
38+ q.push ({p.first ->left , (long long )2 * idx + 1 });
39+
40+ // if right child exist
41+ if (p.first ->right != NULL )
42+ q.push ({p.first ->right , (long long )2 * idx + 2 });
43+ }
44+ }
45+
46+ return res;
47+ }
48+ };
You can’t perform that action at this time.
0 commit comments