I was asked this question in an interview. I started my answer with the naive approach of finding all the subtree and checking if any of them is a bst. In the process, we will record the size of max bst seen so far.
Is there a better approach than this?
What if you do this:
Reverse the weight of your graph
Use Kruskal algorithm in this way.
a. Select the lowest wheighted edge from your set of edges.
b. Create a tree only if adding that edge doesn't break your bst constraint.
c. Remove that edge from your edges set.
You might end up with several trees (Since discarding edges when bst constraint is not satisfied could make you disconnect your original graph), so just select the one with more nodes.
I think of your solution like this:
for each subtree of the tree:
if the subtree is a binary search tree:
compute its size
if it is the largest one found so far:
best = subtree
return best
This is inefficient because it does O(n) work for each subtree, and there are up to n subtrees.
You can do better by walking the whole tree only once.
// Walk the subtree at node. Find the largest subtree that is a binary search tree
// and return that tree in *result. Also return that subtree's size and the range
// of values it covers in *size, *min, and *max.
void
walk(Node *node, Node **result, size_t *size, Value *min, Value *max)
{
Node *result0 = NULL;
size_t size0 = 0;
Value min0, max0;
if (node->left)
walk(node->left, &result0, &size0, &min0, &max0);
Node *result1 = NULL;
size_t size1 = 0;
Value min1, max1;
if (node->right)
walk(node->right, &result1, &size1, &min1, &max1);
// If both subtrees are search trees and node->value falls between them,
// then node is a search tree.
if (result0 == node->left
&& result1 == node->right
&& (node->left == NULL || max0 <= node->value)
&& (node->right == NULL || node->value <= min1))
{
*result = node;
*size = size0 + 1 + size1;
*min = node->left == NULL ? node->value : min0;
*max = node->right == NULL ? node->value : max1;
} else if (size0 >= size1) {
*result = result0;
*size = size0;
*min = min0;
*max = max0;
} else {
*result = result1;
*size = size1;
*min = min1;
*max = max1;
}
}
Node *
findLargestBinarySearchSubtree(Node *root)
{
Node *result;
size_t size;
Value min, max;
walk(root, &result, &size, &min, &max);
return result;
}
This website seems to cover this problem under: Binary Search Tree Checking. Specifically, here's the excerpt to the solution in C++
/*
Returns true if the given tree is a binary search tree
(efficient version).
*/
int isBST2(struct node* node) {
return(isBSTUtil(node, INT_MIN, INT_MAX));
}
/*
Returns true if the given tree is a BST and its
values are >= min and <= max.
*/
int isBSTUtil(struct node* node, int min, int max) {
if (node==NULL) return(true);
// false if this node violates the min/max constraint
if (node->data<min || node->data>max) return(false);
// otherwise check the subtrees recursively,
// tightening the min or max constraint
return
isBSTUtil(node->left, min, node->data) &&
isBSTUtil(node->right, node->data+1, max)
);
}
I assume there is O(n) complexity to solve.
bool is_bst(node * cur)
{
if (cur == NULL)
return true;
// if calculated before cur vertex.
if (hash_set_bst[cur] != -1)
return hash_set_bst[cur];
int left_value = MIN;
int right_value = MAX;
if (cur -> left != NULL)
left_value = cur -> left -> value;
if (cur -> right != NULL)
right_value = cur -> right -> value;
if (cur -> value > left_value && cur -> value < right_value)
{
hash_set_bst[cur] = is_bst(cur->left) && is_bst(cur->right);
return hash_set_bst[cur];
}
else
{
hash_set_bst[cur] = 0;
is_bst(cur->left);
is_bst(cur->right);
return hash_set_bst[cur];
}
}
Now for each node you know if it can start BST or not. Now you need to calculate sub tree sizes and then iterate throgh all nodes and figure out what's the max size having flag if node can start BST.
To calculate sizes you may do the following:
int dfs(node * cur)
{
if (cur == NULL) return 0;
size[cur] = 1 + dfs(cur->left) + dfs(cur->right);
return size[cur];
}
do an in order traversal of the binary tree, if any subtree is BST, in order traversal will produce an ascending sequence, record the size of the tree as you go. when u hit a break point, recursive in order traversal that tree using the break point as root, record its size. pick the biggest one.
How to find the Nth largest node in a BST?
Do I keep a count variable while doing In Order Traversal of a BST? Return the element when the count = N???
The idea is very simple: traverse the tree in decreasing order of the values of each node. When you reach the Nth node, print that node value. Here is the recursive code.
void printNthNode(Node* root, int N)
{
if(root == NULL)
return;
static int index = 0; //These will initialize to zero only once as its static
//For every Node go to the right of that node first.
printNthNode(root->right, N);
//Right has returned and now current node will be greatest
if(++index == N)
{
printf("%d\n", root->data);
return;
}
//And at last go to the left
printNthNode(root->left, N);
}
Edit -
As per the comments below, looks like this is one-time call function due to the static local variable. This can be solved by passing wrapper object for index as follows:
class WrapIndex {
public: int index;
};
and method signature would change to
void printNthNode(Node* root, int N, WrapIndex wrapInd)
Now, we don't need a local static variable; instead use index of the wrapper object. The call would look like
WrapIndex wrapInd = new WrapIndex();
wrapInd.index=0;
printNthNode(root,7,wrapInd);
wrapInd.index=0;
printNthNode(root,2,wrapInd);
Hint: use inorder traversal of the tree. It can print out the items in sorted order, so you can sure find the Nth largest item. Keep a counter as you "walk", incrementing each time you "visit" a node.
Edit: while IVlad's answer is indeed faster, it requires you to keep extra information in the nodes. This answer doesn't but it's O(n). Just pointing out that this is a tradeoff you have to be aware of.
See my answer here. You can do this in O(log n) on average where n = number of nodes. Worst case is still O(n) IF the tree isn't balanced (always O(log n) if it is balanced however). In order traversal is always O(n) however.
Use a inverted inorder tranversal.that is go to right child first instead of left child.
recursively this can be obtained as follows:
The most important issue that a global count must be used when considering recursive solution.
reverseInorder(root){
if(root!=null){
reverseInorder(root->rightChild);
self
reverseInorder(root->leftChild);
}
}
Solution in java
package datastructure.binaryTree;
import datastructure.nodes.BinaryTreeNode;
public class NthElementFromEnd {
private BinaryTree tree=null;
int currCount=0;
public NthElementFromEnd(int[] dataArray) {
this.tree=new BinaryTree(dataArray);
}
private void getElementFromEnd(int n){
getElementFromEnd(this.tree.getRoot(),n);
}
private void getElementFromEnd(BinaryTreeNode node,int n){
if(node!=null){
if(currCount<n)
getElementFromEnd(node.getRightChild(),n);
currCount++;
if(currCount==n)
{
System.out.print(" "+node.getData());
return;
}
if(currCount<n)
getElementFromEnd(node.getLeftChild(),n);
}
}
public static void main(String args[]){
int data[]={1,2,3,4,5,6,7,8,9};
int n=2;
new NthElementFromEnd(data).getElementFromEnd(n);
}
}
int nLargeBST(node *root, int N) {
if (!root || N < 0) {
return -1;
}
nLargeBST(root->left, N);
--N;
if(N == 0) {
return root->val;
}
nLargeBST(root->right, N);
}
This piece of code is from my assignment and one of the condition was not to use
arrays. In order to make the code more compact and readable you can use
stringName.split("|"). Since the method is recursive I use the stringBuilder
which has the following structure: "counter|orderOfElementToFind|dataInrequiredNode"
protected StringBuilder t(StringBuilder s)
{
if (lc != null)
{
lc.t(s);
}
if((s.toString().charAt(s.toString().length() - 1)) == '|')
{
String str = s.toString();
s.delete(0, s.length());
int counter = 0, k = 0;
String strTemp = "", newStrBuilContent = "";
for (int i = 0, c = 0 ; i < str.length(); ++i)
{
if (c == 0)
{
if (str.charAt(i) != '|')
{
strTemp += str.charAt(i);
}
else
{
counter = Integer.parseInt(strTemp);
++c;
strTemp = "";
}
}
else
{
if (str.charAt(i) != '|')
{
strTemp += str.charAt(i);
}
else
{
k = Integer.parseInt(strTemp);
}
}
counter ++;
newStrBuilContent = (counter + "|" + k + "|");
s.append(newStrBuilContent);
if (counter == k)
{
double ldata = this.getData();
s.append(ldata);
}
}
if (rc != null)
{
rc.t(s);
}
return s;
}
and the method call:
// the value of counter ad the beginning is 0 and data
// segment is missing
String s = ("0|" + order +"|");
StringBuilder strBldr = new StringBuilder(s);
String content = sTree.t(strBldr).toString();
s = "";
for (int i = 0, c = 0; i < content.length(); ++i)
{
if (c < 2)
{
if (content.charAt(i) == '|')
{
++c;
}
}
else
{
s += content.charAt(i);
}
}
`
Maintain size of subtree at eachnode(root.size some thing like that). for example {2,3,1} is a binary tree with root 2 then the size of node (2) is 3, node (1) size is 1, and node (2) size is 1
if u want to find 4 th larget element in the tree with root node size 23 , think about its rank
the max element rank is 23, because the root node size is 23. so 4 th largest element rank is 23-4+1= 20
so we have to find 20th rank element in the given tree
initially declare a rank=0 flag to zero
starting from root node find its rank (rank+ size of left child + 1) for example left child size is 16 then root element rank is 17(rank+size of left child +1)
so we have to look for the element with the rank 20. so obviously we have to traverse to its right child
traverse to right child and based on above formula find right child rank(based on above formula, note: now rank flag value is is 17),decide whether to go right or left based on the rank
repeat this process recursevely untill we found rank==20
I would do it by going though the tree from biggest to smallest element and returning value when asked position is reached. I implemented similar task for second largest value. Value of 2 is hardcoded, but is it easy to change with additional parameter :)
void BTree::findSecondLargestValueUtil(Node* r, int &c, int &v)
{
if(r->right) {
this->findSecondLargestValueUtil(r->right, c, v);
}
c++;
if(c==2) {
v = r->value;
return;
}
if(r->left) {
this->findSecondLargestValueUtil(r->left, c, v);
}
}
int BTree::findSecondLargestValue()
{
int c = 0;
int v = -1;
this->findSecondLargestValueUtil(this->root, c, v);
return v;
}
// C++ program to find k'th largest element in BST
#include<iostream>
using namespace std;
struct Node
{
int key;
Node *left, *right;
};
// A utility function to create a new BST node
Node *newNode(int item)
{
Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// A function to find k'th largest element in a given tree.
void kthLargestUtil(Node *root, int k, int &c)
{
// Base cases, the second condition is important to
// avoid unnecessary recursive calls
if (root == NULL || c >= k)
return;
// Follow reverse inorder traversal so that the
// largest element is visited first
kthLargestUtil(root->right, k, c);
// Increment count of visited nodes
c++;
// If c becomes k now, then this is the k'th largest
if (c == k)
{
cout << "K'th largest element is "
<< root->key << endl;
return;
}
// Recur for left subtree
kthLargestUtil(root->left, k, c);
}
// Function to find k'th largest element
void kthLargest(Node *root, int k)
{
// Initialize count of nodes visited as 0
int c = 0;
// Note that c is passed by reference
kthLargestUtil(root, k, c);
}
/* A utility function to insert a new node with given key in BST */
Node* insert(Node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
}
// Driver Program to test above functions
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
Node *root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
int c = 0;
for (int k=1; k<=7; k++)
kthLargest(root, k);
return 0;
}
Swift version. This follows closely with what Vallabh Patade said. The counter is increased by 1 when it tries to go through a node that has no child though. A bit different than his.
class BinaryNode {
var val: Int
var left: BinaryNode?
var right: BinaryNode?
init(value: Int) {
self.val = value
}
}
func findMaxValue(_ n: Int, from root: BinaryNode?) {
var counter = 0
maxValue(counter: &counter, n: n, node: root)
}
private func maxValue(counter: inout Int, n: Int, node: BinaryNode?) {
if node == nil {
counter += 1
return
}
maxValue(counter: &counter, n: n, node: node?.right)
// If the counter has reached the nth node we're looking for.
if counter == n {
if let val = node?.val { print(val) }
}
maxValue(counter: &counter, n: n, node: node?.left)
}
Here is how you can do this by a slight modification of the in-order traversal of the binary search tree - we are finding the kth largest element;
void kthLargest(Node node, int k, int count) {
if(node != null) {
nthLargest(node.left,k,count); //traversing the left node
//while visit the node we do the following
count++; // increment the count and check if that is equal to k
if ( count == k ) {
System.out.println("Node found "+node.value);
}
nthLargest(node.right,k,count); //traversing the right node
}
}
But the problem in this way you are going to reach the kth smallest element and hence you method call should be this: as kth largest element = (n-k)th smallest element.
nthLargest(root,n-k,0);
K’th Largest Element in BST . Learn how to think for such problem and solve with recursion . Kth Larget Explanation Recursion
I need to find the kth smallest element in the binary search tree without using any static/global variable. How to achieve it efficiently?
The solution that I have in my mind is doing the operation in O(n), the worst case since I am planning to do an inorder traversal of the entire tree. But deep down I feel that I am not using the BST property here. Is my assumptive solution correct or is there a better one available ?
Here's just an outline of the idea:
In a BST, the left subtree of node T contains only elements smaller than the value stored in T. If k is smaller than the number of elements in the left subtree, the kth smallest element must belong to the left subtree. Otherwise, if k is larger, then the kth smallest element is in the right subtree.
We can augment the BST to have each node in it store the number of elements in its left subtree (assume that the left subtree of a given node includes that node). With this piece of information, it is simple to traverse the tree by repeatedly asking for the number of elements in the left subtree, to decide whether to do recurse into the left or right subtree.
Now, suppose we are at node T:
If k == num_elements(left subtree of T), then the answer we're looking for is the value in node T.
If k > num_elements(left subtree of T), then obviously we can ignore the left subtree, because those elements will also be smaller than the kth smallest. So, we reduce the problem to finding the k - num_elements(left subtree of T) smallest element of the right subtree.
If k < num_elements(left subtree of T), then the kth smallest is somewhere in the left subtree, so we reduce the problem to finding the kth smallest element in the left subtree.
Complexity analysis:
This takes O(depth of node) time, which is O(log n) in the worst case on a balanced BST, or O(log n) on average for a random BST.
A BST requires O(n) storage, and it takes another O(n) to store the information about the number of elements. All BST operations take O(depth of node) time, and it takes O(depth of node) extra time to maintain the "number of elements" information for insertion, deletion or rotation of nodes. Therefore, storing information about the number of elements in the left subtree keeps the space and time complexity of a BST.
A simpler solution would be to do an inorder traversal and keep track of the element currently to be printed (without printing it). When we reach k, print the element and skip rest of tree traversal.
void findK(Node* p, int* k) {
if(!p || k < 0) return;
findK(p->left, k);
--k;
if(k == 0) {
print p->data;
return;
}
findK(p->right, k);
}
public int ReturnKthSmallestElement1(int k)
{
Node node = Root;
int count = k;
int sizeOfLeftSubtree = 0;
while(node != null)
{
sizeOfLeftSubtree = node.SizeOfLeftSubtree();
if (sizeOfLeftSubtree + 1 == count)
return node.Value;
else if (sizeOfLeftSubtree < count)
{
node = node.Right;
count -= sizeOfLeftSubtree+1;
}
else
{
node = node.Left;
}
}
return -1;
}
this is my implementation in C# based on the algorithm above just thought I'd post it so people can understand better it works for me
thank you IVlad
//add a java version without recursion
public static <T> void find(TreeNode<T> node, int num){
Stack<TreeNode<T>> stack = new Stack<TreeNode<T>>();
TreeNode<T> current = node;
int tmp = num;
while(stack.size() > 0 || current!=null){
if(current!= null){
stack.add(current);
current = current.getLeft();
}else{
current = stack.pop();
tmp--;
if(tmp == 0){
System.out.println(current.getValue());
return;
}
current = current.getRight();
}
}
}
A simpler solution would be to do an inorder traversal and keep track of the element currently to be printed with a counter k. When we reach k, print the element. The runtime is O(n). Remember the function return type can not be void, it has to return its updated value of k after each recursive call. A better solution to this would be an augmented BST with a sorted position value at each node.
public static int kthSmallest (Node pivot, int k){
if(pivot == null )
return k;
k = kthSmallest(pivot.left, k);
k--;
if(k == 0){
System.out.println(pivot.value);
}
k = kthSmallest(pivot.right, k);
return k;
}
You can use iterative inorder traversal:
http://en.wikipedia.org/wiki/Tree_traversal#Iterative_Traversal
with a simple check for kth element after poping a node out of the stack.
Given just a plain binary search tree, about all you can do is start from the smallest, and traverse upward to find the right node.
If you're going to do this very often, you can add an attribute to each node signifying how many nodes are in its left sub-tree. Using that, you can descend the tree directly to the correct node.
Recursive In-order Walk with a counter
Time Complexity: O( N ), N is the number of nodes
Space Complexity: O( 1 ), excluding the function call stack
The idea is similar to #prasadvk solution, but it has some shortcomings (see notes below), so I am posting this as a separate answer.
// Private Helper Macro
#define testAndReturn( k, counter, result ) \
do { if( (counter == k) && (result == -1) ) { \
result = pn->key_; \
return; \
} } while( 0 )
// Private Helper Function
static void findKthSmallest(
BstNode const * pn, int const k, int & counter, int & result ) {
if( ! pn ) return;
findKthSmallest( pn->left_, k, counter, result );
testAndReturn( k, counter, result );
counter += 1;
testAndReturn( k, counter, result );
findKthSmallest( pn->right_, k, counter, result );
testAndReturn( k, counter, result );
}
// Public API function
void findKthSmallest( Bst const * pt, int const k ) {
int counter = 0;
int result = -1; // -1 := not found
findKthSmallest( pt->root_, k, counter, result );
printf("%d-th element: element = %d\n", k, result );
}
Notes (and differences from #prasadvk's solution):
if( counter == k ) test is required at three places: (a) after left-subtree, (b) after root, and (c) after right subtree. This is to ensure that kth element is detected for all locations, i.e. irrespective of the subtree it is located.
if( result == -1 ) test required to ensure only the result element is printed, otherwise all the elements starting from the kth smallest up to the root are printed.
For not balanced searching tree, it takes O(n).
For balanced searching tree, it takes O(k + log n) in the worst case but just O(k) in Amortized sense.
Having and managing the extra integer for every node: the size of the sub-tree gives O(log n) time complexity.
Such balanced searching tree is usually called RankTree.
In general, there are solutions (based not on tree).
Regards.
This works well: status : is the array which holds whether element is found. k : is kth element to be found. count : keeps track of number of nodes traversed during the tree traversal.
int kth(struct tree* node, int* status, int k, int count)
{
if (!node) return count;
count = kth(node->lft, status, k, count);
if( status[1] ) return status[0];
if (count == k) {
status[0] = node->val;
status[1] = 1;
return status[0];
}
count = kth(node->rgt, status, k, count+1);
if( status[1] ) return status[0];
return count;
}
While this is definitely not the optimal solution to the problem, it is another potential solution which I thought some people might find interesting:
/**
* Treat the bst as a sorted list in descending order and find the element
* in position k.
*
* Time complexity BigO ( n^2 )
*
* 2n + sum( 1 * n/2 + 2 * n/4 + ... ( 2^n-1) * n/n ) =
* 2n + sigma a=1 to n ( (2^(a-1)) * n / 2^a ) = 2n + n(n-1)/4
*
* #param t The root of the binary search tree.
* #param k The position of the element to find.
* #return The value of the element at position k.
*/
public static int kElement2( Node t, int k ) {
int treeSize = sizeOfTree( t );
return kElement2( t, k, treeSize, 0 ).intValue();
}
/**
* Find the value at position k in the bst by doing an in-order traversal
* of the tree and mapping the ascending order index to the descending order
* index.
*
*
* #param t Root of the bst to search in.
* #param k Index of the element being searched for.
* #param treeSize Size of the entire bst.
* #param count The number of node already visited.
* #return Either the value of the kth node, or Double.POSITIVE_INFINITY if
* not found in this sub-tree.
*/
private static Double kElement2( Node t, int k, int treeSize, int count ) {
// Double.POSITIVE_INFINITY is a marker value indicating that the kth
// element wasn't found in this sub-tree.
if ( t == null )
return Double.POSITIVE_INFINITY;
Double kea = kElement2( t.getLeftSon(), k, treeSize, count );
if ( kea != Double.POSITIVE_INFINITY )
return kea;
// The index of the current node.
count += 1 + sizeOfTree( t.getLeftSon() );
// Given any index from the ascending in order traversal of the bst,
// treeSize + 1 - index gives the
// corresponding index in the descending order list.
if ( ( treeSize + 1 - count ) == k )
return (double)t.getNumber();
return kElement2( t.getRightSon(), k, treeSize, count );
}
signature:
Node * find(Node* tree, int *n, int k);
call as:
*n = 0;
kthNode = find(root, n, k);
definition:
Node * find ( Node * tree, int *n, int k)
{
Node *temp = NULL;
if (tree->left && *n<k)
temp = find(tree->left, n, k);
*n++;
if(*n==k)
temp = root;
if (tree->right && *n<k)
temp = find(tree->right, n, k);
return temp;
}
Well here is my 2 cents...
int numBSTnodes(const Node* pNode){
if(pNode == NULL) return 0;
return (numBSTnodes(pNode->left)+numBSTnodes(pNode->right)+1);
}
//This function will find Kth smallest element
Node* findKthSmallestBSTelement(Node* root, int k){
Node* pTrav = root;
while(k > 0){
int numNodes = numBSTnodes(pTrav->left);
if(numNodes >= k){
pTrav = pTrav->left;
}
else{
//subtract left tree nodes and root count from 'k'
k -= (numBSTnodes(pTrav->left) + 1);
if(k == 0) return pTrav;
pTrav = pTrav->right;
}
return NULL;
}
This is what I though and it works. It will run in o(log n )
public static int FindkThSmallestElemet(Node root, int k)
{
int count = 0;
Node current = root;
while (current != null)
{
count++;
current = current.left;
}
current = root;
while (current != null)
{
if (count == k)
return current.data;
else
{
current = current.left;
count--;
}
}
return -1;
} // end of function FindkThSmallestElemet
Well we can simply use the in order traversal and push the visited element onto a stack.
pop k number of times, to get the answer.
we can also stop after k elements
Solution for complete BST case :-
Node kSmallest(Node root, int k) {
int i = root.size(); // 2^height - 1, single node is height = 1;
Node result = root;
while (i - 1 > k) {
i = (i-1)/2; // size of left subtree
if (k < i) {
result = result.left;
} else {
result = result.right;
k -= i;
}
}
return i-1==k ? result: null;
}
The Linux Kernel has an excellent augmented red-black tree data structure that supports rank-based operations in O(log n) in linux/lib/rbtree.c.
A very crude Java port can also be found at http://code.google.com/p/refolding/source/browse/trunk/core/src/main/java/it/unibo/refolding/alg/RbTree.java, together with RbRoot.java and RbNode.java. The n'th element can be obtained by calling RbNode.nth(RbNode node, int n), passing in the root of the tree.
Here's a concise version in C# that returns the k-th smallest element, but requires passing k in as a ref argument (it's the same approach as #prasadvk):
Node FindSmall(Node root, ref int k)
{
if (root == null || k < 1)
return null;
Node node = FindSmall(root.LeftChild, ref k);
if (node != null)
return node;
if (--k == 0)
return node ?? root;
return FindSmall(root.RightChild, ref k);
}
It's O(log n) to find the smallest node, and then O(k) to traverse to k-th node, so it's O(k + log n).
http://www.geeksforgeeks.org/archives/10379
this is the exact answer to this question:-
1.using inorder traversal on O(n) time
2.using Augmented tree in k+log n time
I couldn't find a better algorithm..so decided to write one :)
Correct me if this is wrong.
class KthLargestBST{
protected static int findKthSmallest(BSTNode root,int k){//user calls this function
int [] result=findKthSmallest(root,k,0);//I call another function inside
return result[1];
}
private static int[] findKthSmallest(BSTNode root,int k,int count){//returns result[]2 array containing count in rval[0] and desired element in rval[1] position.
if(root==null){
int[] i=new int[2];
i[0]=-1;
i[1]=-1;
return i;
}else{
int rval[]=new int[2];
int temp[]=new int[2];
rval=findKthSmallest(root.leftChild,k,count);
if(rval[0]!=-1){
count=rval[0];
}
count++;
if(count==k){
rval[1]=root.data;
}
temp=findKthSmallest(root.rightChild,k,(count));
if(temp[0]!=-1){
count=temp[0];
}
if(temp[1]!=-1){
rval[1]=temp[1];
}
rval[0]=count;
return rval;
}
}
public static void main(String args[]){
BinarySearchTree bst=new BinarySearchTree();
bst.insert(6);
bst.insert(8);
bst.insert(7);
bst.insert(4);
bst.insert(3);
bst.insert(4);
bst.insert(1);
bst.insert(12);
bst.insert(18);
bst.insert(15);
bst.insert(16);
bst.inOrderTraversal();
System.out.println();
System.out.println(findKthSmallest(bst.root,11));
}
}
Here is the java code,
max(Node root, int k) - to find kth largest
min(Node root, int k) - to find kth Smallest
static int count(Node root){
if(root == null)
return 0;
else
return count(root.left) + count(root.right) +1;
}
static int max(Node root, int k) {
if(root == null)
return -1;
int right= count(root.right);
if(k == right+1)
return root.data;
else if(right < k)
return max(root.left, k-right-1);
else return max(root.right, k);
}
static int min(Node root, int k) {
if (root==null)
return -1;
int left= count(root.left);
if(k == left+1)
return root.data;
else if (left < k)
return min(root.right, k-left-1);
else
return min(root.left, k);
}
this would work too. just call the function with maxNode in the tree
def k_largest(self, node , k):
if k < 0 :
return None
if k == 0:
return node
else:
k -=1
return self.k_largest(self.predecessor(node), k)
I think this is better than the accepted answer because it doesn't need to modify the original tree node to store the number of it's children nodes.
We just need to use the in-order traversal to count the smallest node from the left to right, stop searching once the count equals to K.
private static int count = 0;
public static void printKthSmallestNode(Node node, int k){
if(node == null){
return;
}
if( node.getLeftNode() != null ){
printKthSmallestNode(node.getLeftNode(), k);
}
count ++ ;
if(count <= k )
System.out.println(node.getValue() + ", count=" + count + ", k=" + k);
if(count < k && node.getRightNode() != null)
printKthSmallestNode(node.getRightNode(), k);
}
Best approach is already there.But I'd like to add a simple Code for that
int kthsmallest(treenode *q,int k){
int n = size(q->left) + 1;
if(n==k){
return q->val;
}
if(n > k){
return kthsmallest(q->left,k);
}
if(n < k){
return kthsmallest(q->right,k - n);
}
}
int size(treenode *q){
if(q==NULL){
return 0;
}
else{
return ( size(q->left) + size(q->right) + 1 );
}}
Using auxiliary Result class to track if node is found and current k.
public class KthSmallestElementWithAux {
public int kthsmallest(TreeNode a, int k) {
TreeNode ans = kthsmallestRec(a, k).node;
if (ans != null) {
return ans.val;
} else {
return -1;
}
}
private Result kthsmallestRec(TreeNode a, int k) {
//Leaf node, do nothing and return
if (a == null) {
return new Result(k, null);
}
//Search left first
Result leftSearch = kthsmallestRec(a.left, k);
//We are done, no need to check right.
if (leftSearch.node != null) {
return leftSearch;
}
//Consider number of nodes found to the left
k = leftSearch.k;
//Check if current root is the solution before going right
k--;
if (k == 0) {
return new Result(k - 1, a);
}
//Check right
Result rightBalanced = kthsmallestRec(a.right, k);
//Consider all nodes found to the right
k = rightBalanced.k;
if (rightBalanced.node != null) {
return rightBalanced;
}
//No node found, recursion will continue at the higher level
return new Result(k, null);
}
private class Result {
private final int k;
private final TreeNode node;
Result(int max, TreeNode node) {
this.k = max;
this.node = node;
}
}
}
Python Solution
Time Complexity : O(n)
Space Complexity : O(1)
Idea is to use Morris Inorder Traversal
class Solution(object):
def inorderTraversal(self, current , k ):
while(current is not None): #This Means we have reached Right Most Node i.e end of LDR traversal
if(current.left is not None): #If Left Exists traverse Left First
pre = current.left #Goal is to find the node which will be just before the current node i.e predecessor of current node, let's say current is D in LDR goal is to find L here
while(pre.right is not None and pre.right != current ): #Find predecesor here
pre = pre.right
if(pre.right is None): #In this case predecessor is found , now link this predecessor to current so that there is a path and current is not lost
pre.right = current
current = current.left
else: #This means we have traverse all nodes left to current so in LDR traversal of L is done
k -= 1
if(k == 0):
return current.val
pre.right = None #Remove the link tree restored to original here
current = current.right
else: #In LDR LD traversal is done move to R
k -= 1
if(k == 0):
return current.val
current = current.right
return 0
def kthSmallest(self, root, k):
return self.inorderTraversal( root , k )
public int kthSmallest(TreeNode root, int k) {
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
while (true) {
while (root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
k = k - 1;
if (k == 0) return root.val;
root = root.right;
}
}
Here are the steps:
1.Add a field to each node indicating the size of the tree it roots. This supports operation in O(logN) average time.
2.To save space, one field indicating the size of a node it roots is enough. We don't need to save both the left subtree and right subtree size.
3.Do an inorder traversal until LeftTree == K, LeftTree = Size(T->Left) + 1.
4.Here is the sample code:
int Size(SearchTree T)
{
if(T == NULL) return 0;
return T->Size;
}
Position KthSmallest(SearchTree T, int K)
{
if(T == NULL) return NULL;
int LeftTree;
LeftTree = Size(T->Left) + 1;
if(LeftTree == K) return T;
if(LeftTree > K){
T = KthSmallest(T->Left, K);
}else if(LeftTree < K){
T = KthSmallest(T->Right, K - LeftTree);
}
return T;
}
5.Similarly, we can also get the KthLargest function.
i wrote a neat function to calculate the kth smallest element. I uses in-order traversal and stops when the it reaches the kth smallest element.
void btree::kthSmallest(node* temp, int& k){
if( temp!= NULL) {
kthSmallest(temp->left,k);
if(k >0)
{
if(k==1)
{
cout<<temp->value<<endl;
return;
}
k--;
}
kthSmallest(temp->right,k); }}
public static Node kth(Node n, int k){
Stack<Node> s=new Stack<Node>();
int countPopped=0;
while(!s.isEmpty()||n!=null){
if(n!=null){
s.push(n);
n=n.left;
}else{
node=s.pop();
countPopped++;
if(countPopped==k){
return node;
}
node=node.right;
}
}
}