Saturday, March 27, 2010

To find the kth largest element in a Binary Search Tree, BST

1. Count the number of elements in a tree.

int nodeCount = GetNumberOfNodes(struct Node* root);

2. Traverse the tree using inorder traversal

In-order traversal is Left, Root node, Right

InorderTraversal(root, 0, count);

Root = root node of the tree
nodeCount = number of nodes in a tree
currNode = current node number
K = kth largest element in a tree

struct Node
{
int data;
struct Node* left;
struct Node* right;
};

InorderTraversal(struct Node* root, int currNode, int nodeCount)
{
if (nodeCount - currNode == k)
{
printf(“%d th largest element is: %d”, k, root->data);
break;
}

if (node->left != NULL)
InorderTraversal(node->left);
else if(node->right != NULL)
InorderTraversal(node->right);

}

Note: By traversing the BST tree using in-order, means we are traversing the tree in a sorted order. So that we will get the sorted array. Therefore, kth largest element is arr[numberOfNodesInaBST-k]; and kth smallest element is
Arr[k];

No comments: