#include #include #include using namespace std; //construction of binary search tree template class BinaryTreeNode { public: T data; BinaryTreeNode* left; BinaryTreeNode* right; BinaryTreeNode(T data){ this->data=data; left=NULL; right=NULL; } ~BinaryTreeNode(){ delete left; delete right; } }; //taking input BinaryTreeNode* takeInput(){ int rootData; cout<<"Enter root data"<>rootData; if(rootData==-1) return NULL; BinaryTreeNode* root=new BinaryTreeNode(rootData); BinaryTreeNode* leftChild=takeInput(); BinaryTreeNode* rightChild=takeInput(); root->left=leftChild; root->right=rightChild; return root; } //printing binary tree void printTree(BinaryTreeNode* root) { if(root==NULL) return; cout<data<<":"; if(root->left){ cout<<"L"<left->data<<" "; } if(root->right){ cout<<"R"<right->data<<" "; } cout<left); printTree(root->right); } //sorted array to BST BinaryTreeNode* sortedArrayToBst(int arr[],int start, int end){ //base case if (start > end) return NULL; int mid = (start+end)/2; BinaryTreeNode* root = new BinaryTreeNode(arr[mid]); root->left = sortedArrayToBst(arr,start,mid-1); root->right = sortedArrayToBst(arr,mid+1,end); return root; } //finding the path between the nodes of a bst vector* getRootToNodePath(BinaryTreeNode* root, int data){ if(root==NULL) return NULL; //root agar null hua to seedhe null return kar denge //aur agar root me hi data hua then root ke data ko vector me push krke //return kr denge if(root->data == data){ vector* output = new vector(); output->push_back(root->data); return output; } //if root me data nhi hua to then ek baar right me and ek baar left me search krenge vector* leftOutput = getRootToNodePath(root->left,data); if(leftOutput!=NULL){ leftOutput->push_back(root->data); return leftOutput; } vector* rightOutput = getRootToNodePath(root->right,data); if(rightOutput!=NULL){ rightOutput->push_back(root->data); return rightOutput; }else{ return NULL; } } // 1 2 3 4 5 6 7 -1 -1 -1 -1 8 9 -1 -1 -1 -1 -1 -1 int main() { /* array to bst int arr[]={1,2,3,4,5,6,7}; int n = sizeof(arr)/sizeof(arr[0]); BinaryTreeNode* root = sortedArrayToBst(arr,0,n); printTree(root); */ BinaryTreeNode* root = takeInput(); vector* output = getRootToNodePath(root,8); for(int i=0;isize();i++){ cout<at(i)<