-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTree_LineByLineTraversal.cpp
More file actions
45 lines (40 loc) · 1002 Bytes
/
Tree_LineByLineTraversal.cpp
File metadata and controls
45 lines (40 loc) · 1002 Bytes
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
/*
Your Task:
This is a function problem. You don't need to read input. Just complete the function levelOrder() that takes nodes as parameter and prints level order line-by-line. The newline for every test case is automatically appended by the driver code.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
*/
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node(int x){
data = x;
left = right = NULL;
}
};
void levelOrder(Node* node)
{
//Your code here
if(node==NULL) return;
queue<Node*>q;
q.push(node);
q.push(NULL);
while(q.size()>1){
Node *curr = q.front();
q.pop();
if(curr==NULL){
cout<<"$ ";
q.push(NULL);
continue;
}
cout<<curr->data<<" ";
if(curr->left != NULL)
q.push(curr->left);
if(curr->right != NULL)
q.push(curr->right);
}
if(q.size()==1)
cout<<"$";
}