// Java program to find the length of largest word
// in ternary search tree
public class GFG {
static final int MAX = 50;
// A node of ternary search tree
static class Node
{
char data;
// True if this character is last
// character of one of the words
int isEndOfString = 1;
Node left, eq, right;
// constructor
Node(char data)
{
this.data = data;
isEndOfString = 0;
left = null;
eq = null;
right = null;
}
}
// Function to insert a new word in a Ternary
// Search Tree
static Node insert(Node root, String word, int i)
{
// Base Case: Tree is empty
if (root == null)
root = new Node(word.charAt(i));
// If current character of word is smaller
// than root's character, then insert this
// word in left subtree of root
if (word.charAt(i) < root.data)
root.left = insert(root.left, word, i);
// If current character of word is greater
// than root's character, then insert this
// word in right subtree of root
else if (word.charAt(i) > root.data)
root.right = insert(root.right, word, i);
// If current character of word is same as
// root's character,
else
{
if (i + 1 < word.length())
root.eq = insert(root.eq, word, i + 1);
// the last character of the word
else
root.isEndOfString = 1;
}
return root;
}
// Function to find max of three numbers
static int max(int a, int b, int c)
{
int max;
if (a >= b && a >= c)
max = a;
else if (b >= a && b >= c)
max = b;
else
max = c;
return max;
}
// Function to find length of largest word in TST
static int maxLengthTST(Node root)
{
if (root == null)
return 0;
return max(maxLengthTST(root.left),
maxLengthTST(root.eq)+1,
maxLengthTST(root.right));
}
// Driver program to test above functions
public static void main(String args[])
{
Node root = null;
root = insert(root, "Prakriti", 0);
root = insert(root, "Raghav", 0);
root = insert(root, "Rashi", 0);
root = insert(root, "Sunidhi", 0);
int value = maxLengthTST(root);
System.out.println("Length of largest word in "+
"ternary search tree is: "+ value);
}
}
// This code is contributed by Sumit Ghosh