#include<stdio.h>
#include<malloc.h>
struct treenode{
int data;
struct treenode * left;
struct treenode * right;
};
int no_of_nodes(struct treenode * node)
{
if(node == NULL)
return 0;
else
return(1 + no_of_nodes(node->left) + no_of_nodes(node->right));
}
int findkthmin(struct treenode * node, int k)
{
int no_nodes = no_of_nodes(node->left);
if (no_nodes == k-1)
return node->data;
if (no_nodes >= k)
return findkthmin(node->left,k);
else
return findkthmin(node->right, (k - no_nodes - 1));
}
void main()
{
struct treenode * tree;
int k, min;
tree = createtree(); /*create a BST*/
scanf("%d",&k);
if (no_of_nodes(tree) < k)
{
printf("Number of nodes in tree are less than %d \n",k);
return;
}
min = findkthmin(tree, k);
printf("kth min element = %d\n",min);
}
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.
Kth Minimum element in a tree
Question: WAP to find Kth minimum element in a Binary Searth Tree.
Answer:
Count number of nodes in the tree if they are less then k return.
If (no_of_nodes(node->left) == k-1) return node->data
If (no_of_nodes(node->left) >= k) findkthmin(node->left,k)
else findkthmin(node->right, (k - no_of_nodes(node->left) -1))
Code:
This solution can be optimized by saving the no of nodes in each subtree while calling no_of_nodes(tree) for root.
For finding kth maximum element, similar logic can be used.
under:
tree
Find us on Facebook
I write about
- Algorithm (31)
- Amazon EC2 (3)
- Amazon Interview (9)
- Amazon S3 (5)
- Amazon SimpleDB (5)
- Amazon SQS (1)
- Architecture (3)
- Arrays/Strings (32)
- backtracking (1)
- Brain Teasers (8)
- C++ (3)
- Cloud Computing (14)
- Design Pattern (2)
- Dynamic programming (11)
- Facebook Interview (3)
- General (14)
- Git (2)
- Google Interview (6)
- Humour (1)
- Interviews (7)
- Link List (8)
- Mac (2)
- Mathematics (3)
- MIcrosoft Interview (4)
- Miscellany (1)
- python (3)
- queue (1)
- Ruby (9)
- tree (19)
- web development (1)
Will the inorder traversal will not be a better idea..
This is really inefficient. Implement a stack to recurse yourself and implement an in-order tree traversal algorithm.