Code: Print Elements in Range
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 contains two integers, that denote the value of k1 and k2.
The first and only line of output prints the elements which are in range k1 and k2 (both inclusive). Print the elements in increasing order.
Time Limit: 1 second
8 5 10 2 6 -1 -1 -1 -1 -1 7 -1 -1
6 10
6 7 8 10
/**********************************************************
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; } };
***********************************************************/
void elementsInRangeK1K2(BinaryTreeNode<int>* root, int k1, int k2) { // Write your code here if(root==NULL)return ; elementsInRangeK1K2(root->left,k1,k2); if (root->data>=k1 && root->data<=k2) cout << root->data << " "; elementsInRangeK1K2(root->right,k1,k2); // else if(k1>=root->data && k2<=root->data)cout<<root->right->data<<" ";}
Comments
Post a Comment