-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathBinaryTree_implementation.cpp
111 lines (82 loc) · 1.66 KB
/
BinaryTree_implementation.cpp
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
#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;
Node(int data){
this->data=data;
left=NULL;
right=NULL;
}
};
Node* buildTree(){
int data;
cin>>data;
if(data==-1){
return NULL;
}
Node* root = new Node(data);
root->left = buildTree();
root->right=buildTree();
return root;
}
void levelwiseprint(Node* root){
queue<Node*> q;
q.push(root);
q.push(NULL);
while(!q.empty()){
Node* temp = q.front();
q.pop();
if(temp==NULL){
cout<<endl;
if(!q.empty()){
q.push(NULL);
}
}else{
cout<<temp->data<<" ";
if(temp->left){
q.push(temp->left);
}
if(temp->right){
q.push(temp->right);
}
}
}
}
void inorder(Node* root){
if(root==NULL){
return;
}
//LNR
inorder(root->left);
cout<<root->data<<" ";
inorder(root->right);
}
void leftview(Node* root, vector<int> &ans,int level){
if(root==NULL) return;
if(level==ans.size()){
ans.push_back(root->data);
}
leftview(root->left,ans,level+1);
leftview(root->right,ans,level+1);
}
int main(){
Node* root=NULL;
root=buildTree();
levelwiseprint(root);
cout<<endl;
cout<<"Inorder traversal"<<":- ";
inorder(root);
cout<<endl;
vector<int> ans;
int level = 0;
leftview(root,ans,level);
cout<<"left view"<<":-";
for(auto value : ans){
cout<<value<<" ";
}
cout<<endl;
return 0;
}