A Binary Search Tree is given and we need to find the Kth largest in that tree. Root is given...
Approach :
Two approaches can be taken.
1. Recursive approach
2. Iterative Approach
Both the approaches code is below in C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace kthElement
{
// Tree Node Definition
public class Tree
{
public int item;
public Tree left;
public Tree right;
public Tree(int val)
{
item = val;
left = null;
right = null;
}
}
// Program
class Program
{
static void Main(string[] args)
{
/* Constructed binary tree is
10
/ \
7 30
/ \ /
4 8 16
/
2
*/
Tree root = new Tree(10);
root.left = new Tree(7);
root.right = new Tree(30);
root.left.left = new Tree(4);
root.left.right = new Tree(8);
root.right.left = new Tree(16);
root.left.left.left = new Tree(2);
for (int i = 1; i < 5; i++)
{
int k = i;
findKthElementRecursive(root, ref k);
k = i;
Tree kthElement = findKthElementIterative(root, k);
if (kthElement != null)
{
Console.WriteLine(kthElement.item);
}
}
}
// Function Implementing Recursive approach
public static void findKthElementRecursive(Tree root, ref int k)
{
if (root == null)
return;
findKthElementRecursive(root.left,ref k);
k--;
if (k == 0)
{
Console.WriteLine(root.item);
}
findKthElementRecursive(root.right, ref k);
}
// Function Implementing iterative approach
// 1. Push current focus tree to stack
// 2. Update the current focus to left sub-tree
// 3. Pop out tree when current focus is null
// 4. Decrement K by 1 and if K is Zero Return the current
// 5. Else Set focus to the pop-up node's right
public static Tree findKthElementIterative(Tree root, int k)
{
if (root == null)
return null;
Tree current = root;
Stack<Tree> st = new Stack<Tree>();
while (st.Count > 0 || current != null)
{
if (current != null)
{
st.Push(current);
current = current.left;
}
else
{
current = st.Pop();
k--;
if (k == 0)
return current;
current = current.right;
}
}
return null;
}
}
}
Recursive approach : O(n)
Iterative approach : O(n)
Hope you must have liked it...
No comments:
Post a Comment