///************** BST QUESTION*************///////////// /// IN THIS QUESTION THEY WILL GIVE US A NUMBER AND IF IT IS PRESENT IN THAT TREE GIVE US TRUE OTHERWISE RETURN FALSE TO JUS /// APPROACH // if we get null return false otherwise if root->data > (number passed) go to the left side else go to right side ///// FIRST APPROACH bool searchInBST(BinaryTreeNode<int> *root, int x){ BinaryTreeNode<int> *temp = root; while(temp != NULL) if(temp->data == x){ return true; } if(temp->data > x){ temp = temp->left; } else{ temp = temp->right; } return false; } ////// second approach bool searchInBST(BinaryTreeNode<int> *root , int x ){ // base case if(root == Null){ return false; } if(root ->data == x){ return true; } if(root->data > x){ return seachInBST(root->left , x ); } else{ return seachInBST(root->right, x ); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter