forked from Ayu-99/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind Path in BST.cpp
72 lines (67 loc) · 1.71 KB
/
Find Path in BST.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
/*
Find Path in BST
Send Feedback
Given a BST and an integer k. Find and return the path from the node with data k and root (if a node with data k is present in given BST). Return null otherwise.
Assume that BST contains all unique elements.
Input Format :
Line 1 : Elements in level order form (separated by space)
(If any node does not have left or right child, take -1 in its place)
Line 2 : Integer k
Output Format :
Path from node k to root
Sample Input :
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
2
Sample Output :
2
5
8
*/
// Following is the Binary Tree node structure
/**************
class BinaryTreeNode {
public :
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T data) {
this -> data = data;
left = NULL;
right = NULL;
}
};
***************/
#include<vector>
vector<int>* findPath(BinaryTreeNode<int> *root , int data){
/* Don't write main().
* Don't read input, it is passed as function argument.
* Return output and don't print it.
* Taking input and printing output is handled automatically.
*/
if(root==NULL){
return NULL;
}
if(root->data==data){
vector<int>* output=new vector<int>();
output->push_back(root->data);
return output;
}
if(root->data>data){
vector<int>* left=findPath(root->left, data);
if(left!=NULL){
left->push_back(root->data);
return left;
}else{
return NULL;
}
}else{
vector<int>* right=findPath(root->right, data);
if(right!=NULL){
right->push_back(root->data);
return right;
}else{
return NULL;
}
}
return NULL;
}