-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathancestors.cpp
104 lines (73 loc) · 1.6 KB
/
ancestors.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
#include<bits/stdc++.h>
using namespace std;
int imax=INT_MIN;
class Node{
public:
int value;
Node* left;
Node* right;
Node(int v){
value=v;
left=NULL;
right=NULL;
}
};
Node* newNode(int v){
Node* node = new Node(v);
return node;
}
void inorder(Node* root){
if(root){
inorder(root->left);
cout<<root->value<<" ";
inorder(root->right);
}
}
Node* insert(Node*& root, int val){
if(root==NULL)
return newNode(val);
else if( val < root->value)
root->left = insert(root->left, val);
else if(val > root->value)
root->right = insert(root->right , val);
return root;
}
void lvlT(Node* root){
queue<Node*>q;
q.push(root);
while(!q.empty()){
Node* temp = q.front(); q.pop();
cout<<temp->value<<" ";
if(temp->left)
q.push(temp->left);
if(temp->right)
q.push(temp->right);
}
}
int printAncestors(Node* root,int target){
if(root==NULL)
return 0;
if(root->value == target)
return 1;
if(printAncestors(root->left,target) || printAncestors(root->right,target)){
cout<<root->value<<" ";
return 1;
}
return 0;
}
int main(){
Node* root=NULL;
root=insert(root,3);
root=insert(root,1);
root=insert(root,5);
root=insert(root,0);
root=insert(root,2);
root=insert(root,4);
root=insert(root,6);
inorder(root);
cout<<endl;
cout<<"\nLevel Order Traversal \n"<<endl;
lvlT(root);
cout<<"\nAncestors : "<<endl;
printAncestors(root,6);
}