File tree 2 files changed +90
-0
lines changed
2 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ class Graph
5
+ {
6
+ int v;
7
+ list<int > *l;
8
+
9
+ public:
10
+ Graph (int v)
11
+ {
12
+ this ->v = v;
13
+ l = new list<int >[v];
14
+ }
15
+ void addEdge (int x, int y)
16
+ {
17
+ l[x].push_back (y);
18
+ l[y].push_back (x);
19
+ }
20
+
21
+ void printAdjList ()
22
+ {
23
+ for (int i = 0 ; i < v; i++)
24
+ {
25
+ cout << " Vertex " << i << " ->" ;
26
+ for (int nbr : l[i])
27
+ {
28
+ cout << nbr << " ," ;
29
+ }
30
+ cout << endl;
31
+ }
32
+ }
33
+ };
34
+
35
+ int main ()
36
+ {
37
+ #ifndef ONLINE_JUDGE
38
+ freopen (" input.txt" , " r" , stdin);
39
+ freopen (" output.txt" , " w" , stdout);
40
+ #endif
41
+
42
+ Graph g (4 );
43
+ g.addEdge (0 , 1 );
44
+ g.addEdge (0 , 2 );
45
+ g.addEdge (2 , 3 );
46
+ g.addEdge (1 , 2 );
47
+
48
+ g.printAdjList ();
49
+ return 0 ;
50
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ // We need to apply Breadth first Search for this given tree.
4
+ // That is why we need a Queue for DS for our problem .
5
+ vector<vector<int >> levelOrder (TreeNode* root) {
6
+ if (!root) return {}; // if Tree is Empty
7
+ vector<vector<int >> ans;
8
+
9
+ // We are taking Queue to do Level Order Traversal
10
+ queue<TreeNode*>q ;
11
+ q.push (root);
12
+
13
+ // We are suppose to set some indication for one level to end , here we chose NULL
14
+ q.push (NULL );
15
+ vector<int > temp ; // vector to keep current array of items
16
+ while (!q.empty ())
17
+ {
18
+ TreeNode *ptr = q.front ();
19
+ q.pop (); // Removing front item and will be adding children for same front element
20
+ // Check for Level Order and push current vector to main answer.
21
+ if (ptr == NULL )
22
+ {
23
+ ans.push_back (temp);
24
+ temp.clear ();
25
+ if (!q.empty ()) q.push (NULL ); // check if atleast one parent element left in queue.
26
+ }
27
+ else
28
+ {
29
+ temp.push_back (ptr->val );
30
+
31
+ // pushing childens of current front element.
32
+ if (ptr->left ) q.push (ptr->left );
33
+ if (ptr->right ) q.push (ptr->right );
34
+ }
35
+
36
+ }
37
+
38
+ return ans;
39
+ }
40
+ };
You can’t perform that action at this time.
0 commit comments