You are given a binary search tree. You task is to find the median of sub tree of Kth smallest node of the tree.
For each testcase, in a new line, print the median of sub tree of Kth smallest node of the tree.
Constraints:
1 <= T <= 30
1 <= Number of nodes <= 100
1 <= Data of a node <= 1000
1 <= K <= Number of nodes
Example:
Input:
1
12 9
50 25 75 15 45 90 11 20 30 49 80 100
Output:
85
For the above question i have wrriten below solution.
Node* inorder(Node* root, int* sm, int k) {
if(root != NULL)
{
inorder(root -> left , sm , k);
if(*sm == k-1)
{
return root;
}
*sm = *sm +1;
inorder(root -> right , sm , k);
}
}
void fillvector(Node* root, vector<int>& v) {
if (root != nullptr) {
fillvector(root->left, v);
v.push_back(root->data);
fillvector(root->right, v);
}
}
int median(Node* node, int k) {
int sm = 0;
Node* kthroot = inorder(node, &sm, k);
vector<int> v;
if(kthroot != NULL)
fillvector(kthroot, v);
int len = v.size();
if (len % 2 != 0) {
return v[len / 2];
} else {
return (v[(len - 1) / 2] + v[len / 2]) / 2;
}
}
Code is not working when i submit on gfg and says segmentation fault (on compiling it is giving the write answer)
But When i change my inorder function code to below then it works fine(rest code is exactly same ).
Node* inorder(Node* root, int* sm, int k)
{
if (root != NULL)
{
Node* leftResult = inorder(root->left, sm, k);
if (leftResult != NULL)
return leftResult;
if (*sm == k - 1)
{
return root;
}
(*sm)++;
Node* rightResult = inorder(root->right, sm, k);
if (rightResult != NULL)
return rightResult;
}
return NULL;
}
Can any abody help me why this is happen?
To find the median of the subtree of the Kth smallest node in a binary search tree (BST), we can follow these steps:
Define a function called
kthSmallestthat takes the BST root node, K, and an empty array as parameters. This function will traverse the BST in an inorder manner and populate the array with the values of the nodes.Implement the
kthSmallestfunction recursively:kthSmalleston the left child.kthSmalleston the right child.Define a function called
findMedianthat takes the BST root node and K as parameters. This function will find the median of the subtree of the Kth smallest node.kthSmallestfunction with the root node, K, and the empty array.Here's the Python code that implements the above steps:
This code will output:
Note that this code assumes that the BST does not contain duplicate values. If there are duplicates, you may need to modify the code slightly to handle them appropriately.