forked from prateek27/Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarytree.cpp
More file actions
113 lines (112 loc) · 1.84 KB
/
Copy pathbinarytree.cpp
File metadata and controls
113 lines (112 loc) · 1.84 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<stdio.h>
#include<stdlib.h>
#include<queue>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
typedef struct node Node;
Node* newnode(int d)
{
Node* node = (Node*)malloc(sizeof(Node));
node->data=d;
node->left=NULL;
node->right=NULL;
return node;
}
void printInorder(struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
void leftview(Node* node)
{
if(node==NULL)
return;
printf("%d ",node->data);
if(node->left!=NULL)
leftview(node->left);
else
leftview(node->right);
}
void rightview(Node* node)
{
if(node==NULL)
return;
printf("%d ",node->data);
if(node->right!=NULL)
rightview(node->right);
else
rightview(node->left);
}
void levelorder(Node* node)
{
queue<Node*> Q;
Q.push(node);
while(!Q.empty())
{
Node* cur=Q.front();
Q.pop();
printf("%d ",cur->data);
if(cur->left!=NULL)
Q.push(cur->left);
if(cur->right!=NULL)
Q.push(cur->right);
}
}
void levelorder2(Node* node)
{
int p1,p2;
queue<Node*> Q;
Q.push(node);
p1=1;
p2=0;
while(!Q.empty())
{
while(p1)
{
Node* cur=Q.front();
Q.pop();
printf("%d ",cur->data);
if(cur->left!=NULL)
{
Q.push(cur->left);
p2++;
}
if(cur->right!=NULL)
{
Q.push(cur->right);
p2++;
}
p1--;
}
printf("\n");
p1=p2;
p2=0;
}
}
int main()
{
Node *root=newnode(1);
root->left=newnode(18);
root->right=newnode(3);
root->left->left=newnode(4);
root->left->right=newnode(5);
root->left->left->right=newnode(6);
// printInorder(root);
leftview(root);
printf("\n");
rightview(root);
printf("\n");
levelorder(root);
printf("\n");
levelorder2(root);
printf("\n");
return 0;
}