Code: Search in BST
The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node.
The following line of input contains an integer, that denotes the value of k.
The first and only line of output contains a boolean value. Print true, if node with data k is present, print false otherwise.
Time Limit: 1 second
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
2
true
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
12
false
/**********************************************************
Following is the Binary Tree Node class structure
template <typename T> class BinaryTreeNode { public : T data; BinaryTreeNode<T> *left; BinaryTreeNode<T> *right;
BinaryTreeNode(T data) { this -> data = data; left = NULL; right = NULL; } };
***********************************************************/
bool searchInBST(BinaryTreeNode<int> *root , int k) { // Write your code here if(root==NULL) return 0; if(root->data==k) return true; if(root->data>k)return searchInBST(root->left,k); if(root->data<k) return searchInBST(root->right,k); }
Comments
Post a Comment