Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
13 Likes
Like
Report

This article is continuation of following five articles:
Ukkonen’s Suffix Tree Construction – Part 1
Ukkonen’s Suffix Tree Construction – Part 2
Ukkonen’s Suffix Tree Construction – Part 3
Ukkonen’s Suffix Tree Construction – Part 4
Ukkonen’s Suffix Tree Construction – Part 5
Please go through Part 1 , Part 2 , Part 3 , Part 4 and Part 5 , before looking at current article, where we have seen few basics on suffix tree, high level ukkonen’s algorithm, suffix link and three implementation tricks and activePoints along with an example string "abcabxabcd" where we went through all phases of building suffix tree.
Here, we will see the data structure used to represent suffix tree and the code implementation.
At that end of Part 5 article, we have discussed some of the operations we will be doing while building suffix tree and later when we use suffix tree in different applications.
There could be different possible data structures we may think of to fulfill the requirements where some data structure may be slow on some operations and some fast. Here we will use following in our implementation:

We will have SuffixTreeNode structure to represent each node in tree. SuffixTreeNode structure will have following members:

This data structure will answer to the required queries quickly as below:

Following is C implementation of Ukkonen's Suffix Tree Construction. The code may look a bit lengthy, probably because of a good amount of comments.

C++
#include<iostream>
#include<cstring>
#include<cstdlib>
#define MAX_CHAR 256
structSuffixTreeNode{
SuffixTreeNode*children[MAX_CHAR];
SuffixTreeNode*suffixLink;
intstart;
int*end;
intsuffixIndex;
};
typedefSuffixTreeNodeNode;
chartext[100];
Node*root=nullptr;
Node*lastNewNode=nullptr;
Node*activeNode=nullptr;
intcount=0;
intactiveEdge=-1;
intactiveLength=0;
intremainingSuffixCount=0;
intleafEnd=-1;
int*rootEnd=nullptr;
int*splitEnd=nullptr;
intsize=-1;
// Function to create a new node in the suffix tree
Node*newNode(intstart,int*end){
count++;
Node*node=newNode;
for(inti=0;i<MAX_CHAR;i++)
node->children[i]=nullptr;
node->suffixLink=root;
node->start=start;
node->end=end;
node->suffixIndex=-1;
returnnode;
}
// Function to calculate the length of an edge
intedgeLength(Node*n){
return*(n->end)-(n->start)+1;
}
// Function to perform walk down in the tree
intwalkDown(Node*currNode){
if(activeLength>=edgeLength(currNode)){
activeEdge=static_cast<int>(text[activeEdge+edgeLength(currNode)])-static_cast<int>(' ');
activeLength-=edgeLength(currNode);
activeNode=currNode;
return1;
}
return0;
}
// Function to extend the suffix tree
voidextendSuffixTree(intpos){
leafEnd=pos;
remainingSuffixCount++;
lastNewNode=nullptr;
while(remainingSuffixCount>0){
if(activeLength==0){
activeEdge=static_cast<int>(text[pos])-static_cast<int>(' ');
}
if(activeNode->children[activeEdge]==nullptr){
activeNode->children[activeEdge]=newNode(pos,&leafEnd);
if(lastNewNode!=nullptr){
lastNewNode->suffixLink=activeNode;
lastNewNode=nullptr;
}
}
else{
Node*next=activeNode->children[activeEdge];
if(walkDown(next)){
continue;
}
if(text[next->start+activeLength]==text[pos]){
if(lastNewNode!=nullptr&&activeNode!=root){
lastNewNode->suffixLink=activeNode;
lastNewNode=nullptr;
}
activeLength++;
break;
}
splitEnd=newint;
*splitEnd=next->start+activeLength-1;
Node*split=newNode(next->start,splitEnd);
activeNode->children[activeEdge]=split;
split->children[static_cast<int>(text[pos])-static_cast<int>(' ')]=newNode(pos,&leafEnd);
next->start+=activeLength;
split->children[activeEdge]=next;
if(lastNewNode!=nullptr){
lastNewNode->suffixLink=split;
}
lastNewNode=split;
}
remainingSuffixCount--;
if(activeNode==root&&activeLength>0){
activeLength--;
activeEdge=static_cast<int>(text[pos-remainingSuffixCount+1])-static_cast<int>(' ');
}
elseif(activeNode!=root){
activeNode=activeNode->suffixLink;
}
}
}
// Function to print characters from index i to j
voidprint(inti,intj){
for(intk=i;k<=j;k++)
std::cout<<text[k];
}
// Function to set suffix index by DFS traversal
voidsetSuffixIndexByDFS(Node*n,intlabelHeight){
if(n==nullptr)return;
if(n->start!=-1){
print(n->start,*(n->end));
}
intleaf=1;
for(inti=0;i<MAX_CHAR;i++){
if(n->children[i]!=nullptr){
if(leaf==1&&n->start!=-1)
std::cout<<" ["<<n->suffixIndex<<"]\n";
leaf=0;
setSuffixIndexByDFS(n->children[i],labelHeight+edgeLength(n->children[i]));
}
}
if(leaf==1){
n->suffixIndex=size-labelHeight;
std::cout<<" ["<<n->suffixIndex<<"]\n";
}
}
// Function to free memory in post-order traversal
voidfreeSuffixTreeByPostOrder(Node*n){
if(n==nullptr)
return;
for(inti=0;i<MAX_CHAR;i++){
if(n->children[i]!=nullptr){
freeSuffixTreeByPostOrder(n->children[i]);
}
}
if(n->suffixIndex==-1)
deleten->end;
deleten;
}
// Function to build the suffix tree
voidbuildSuffixTree(){
size=strlen(text);
rootEnd=newint;
*rootEnd=-1;
root=newNode(-1,rootEnd);
activeNode=root;
for(inti=0;i<size;i++)
extendSuffixTree(i);
intlabelHeight=0;
setSuffixIndexByDFS(root,labelHeight);
freeSuffixTreeByPostOrder(root);
}
// Main function
intmain(intargc,char*argv[]){
strcpy(text,"abbc");
buildSuffixTree();
std::cout<<"Number of nodes in suffix tree are "<<count<<std::endl;
return0;
}
C
// A C program to implement Ukkonen's Suffix Tree Construction 
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX_CHAR 256 
structSuffixTreeNode{
structSuffixTreeNode*children[MAX_CHAR];
//pointer to other node via suffix link 
structSuffixTreeNode*suffixLink;
/*(start, end) interval specifies the edge, by which the 
 node is connected to its parent node. Each edge will 
 connect two nodes, one parent and one child, and 
 (start, end) interval of a given edge will be stored 
 in the child node. Lets say there are two nods A and B 
 connected by an edge with indices (5, 8) then this 
 indices (5, 8) will be stored in node B. */
intstart;
int*end;
/*for leaf nodes, it stores the index of suffix for 
 the path from root to leaf*/
intsuffixIndex;
};
typedefstructSuffixTreeNodeNode;
chartext[100];//Input string 
Node*root=NULL;//Pointer to root node 
/*lastNewNode will point to newly created internal node, 
waiting for it's suffix link to be set, which might get 
a new suffix link (other than root) in next extension of 
same phase. lastNewNode will be set to NULL when last 
newly created internal node (if there is any) got it's 
suffix link reset to new internal node created in next 
extension of same phase. */
Node*lastNewNode=NULL;
Node*activeNode=NULL;
intcount=0;
/*activeEdge is represented as input string character 
index (not the character itself)*/
intactiveEdge=-1;
intactiveLength=0;
// remainingSuffixCount tells how many suffixes yet to 
// be added in tree 
intremainingSuffixCount=0;
intleafEnd=-1;
int*rootEnd=NULL;
int*splitEnd=NULL;
intsize=-1;//Length of input string 
Node*newNode(intstart,int*end)
{
count++;
Node*node=(Node*)malloc(sizeof(Node));
inti;
for(i=0;i<MAX_CHAR;i++)
node->children[i]=NULL;
/*For root node, suffixLink will be set to NULL 
 For internal nodes, suffixLink will be set to root 
 by default in current extension and may change in 
 next extension*/
node->suffixLink=root;
node->start=start;
node->end=end;
/*suffixIndex will be set to -1 by default and 
 actual suffix index will be set later for leaves 
 at the end of all phases*/
node->suffixIndex=-1;
returnnode;
}
intedgeLength(Node*n){
return*(n->end)-(n->start)+1;
}
intwalkDown(Node*currNode)
{
/*activePoint change for walk down (APCFWD) using 
 Skip/Count Trick (Trick 1). If activeLength is greater 
 than current edge length, set next internal node as 
 activeNode and adjust activeEdge and activeLength 
 accordingly to represent same activePoint*/
if(activeLength>=edgeLength(currNode))
{
activeEdge=
(int)text[activeEdge+edgeLength(currNode)]-(int)' ';
activeLength-=edgeLength(currNode);
activeNode=currNode;
return1;
}
return0;
}
voidextendSuffixTree(intpos)
{
/*Extension Rule 1, this takes care of extending all 
 leaves created so far in tree*/
leafEnd=pos;
/*Increment remainingSuffixCount indicating that a 
 new suffix added to the list of suffixes yet to be 
 added in tree*/
remainingSuffixCount++;
/*set lastNewNode to NULL while starting a new phase, 
 indicating there is no internal node waiting for 
 it's suffix link reset in current phase*/
lastNewNode=NULL;
//Add all suffixes (yet to be added) one by one in tree 
while(remainingSuffixCount>0){
if(activeLength==0){
//APCFALZ 
activeEdge=(int)text[pos]-(int)' ';
}
// There is no outgoing edge starting with 
// activeEdge from activeNode 
if(activeNode->children[activeEdge]==NULL)
{
//Extension Rule 2 (A new leaf edge gets created) 
activeNode->children[activeEdge]=
newNode(pos,&leafEnd);
/*A new leaf edge is created in above line starting 
 from an existing node (the current activeNode), and 
 if there is any internal node waiting for it's suffix 
 link get reset, point the suffix link from that last 
 internal node to current activeNode. Then set lastNewNode 
 to NULL indicating no more node waiting for suffix link 
 reset.*/
if(lastNewNode!=NULL)
{
lastNewNode->suffixLink=activeNode;
lastNewNode=NULL;
}
}
// There is an outgoing edge starting with activeEdge 
// from activeNode 
else
{
// Get the next node at the end of edge starting 
// with activeEdge 
Node*next=activeNode->children[activeEdge];
if(walkDown(next))//Do walkdown 
{
//Start from next node (the new activeNode) 
continue;
}
/*Extension Rule 3 (current character being processed 
 is already on the edge)*/
if(text[next->start+activeLength]==text[pos])
{
//If a newly created node waiting for it's 
//suffix link to be set, then set suffix link 
//of that waiting node to current active node 
if(lastNewNode!=NULL&&activeNode!=root)
{
lastNewNode->suffixLink=activeNode;
lastNewNode=NULL;
}
//APCFER3 
activeLength++;
/*STOP all further processing in this phase 
 and move on to next phase*/
break;
}
/*We will be here when activePoint is in middle of 
 the edge being traversed and current character 
 being processed is not on the edge (we fall off 
 the tree). In this case, we add a new internal node 
 and a new leaf edge going out of that new node. This 
 is Extension Rule 2, where a new leaf edge and a new 
 internal node get created*/
splitEnd=(int*)malloc(sizeof(int));
*splitEnd=next->start+activeLength-1;
//New internal node 
Node*split=newNode(next->start,splitEnd);
activeNode->children[activeEdge]=split;
//New leaf coming out of new internal node 
split->children[(int)text[pos]-(int)' ']=
newNode(pos,&leafEnd);
next->start+=activeLength;
split->children[activeEdge]=next;
/*We got a new internal node here. If there is any 
 internal node created in last extensions of same 
 phase which is still waiting for it's suffix link 
 reset, do it now.*/
if(lastNewNode!=NULL)
{
/*suffixLink of lastNewNode points to current newly 
 created internal node*/
lastNewNode->suffixLink=split;
}
/*Make the current newly created internal node waiting 
 for it's suffix link reset (which is pointing to root 
 at present). If we come across any other internal node 
 (existing or newly created) in next extension of same 
 phase, when a new leaf edge gets added (i.e. when 
 Extension Rule 2 applies is any of the next extension 
 of same phase) at that point, suffixLink of this node 
 will point to that internal node.*/
lastNewNode=split;
}
/* One suffix got added in tree, decrement the count of 
 suffixes yet to be added.*/
remainingSuffixCount--;
if(activeNode==root&&activeLength>0)//APCFER2C1 
{
activeLength--;
activeEdge=(int)text[pos-
remainingSuffixCount+1]-(int)' ';
}

//APCFER2C2 
elseif(activeNode!=root)
{
activeNode=activeNode->suffixLink;
}
}
}
voidprint(inti,intj)
{
intk;
for(k=i;k<=j;k++)
printf("%c",text[k]);
}
//Print the suffix tree as well along with setting suffix index 
//So tree will be printed in DFS manner 
//Each edge along with it's suffix index will be printed 
voidsetSuffixIndexByDFS(Node*n,intlabelHeight)
{
if(n==NULL)return;
if(n->start!=-1)//A non-root node 
{
//Print the label on edge from parent to current node 
print(n->start,*(n->end));
}
intleaf=1;
inti;
for(i=0;i<MAX_CHAR;i++)
{
if(n->children[i]!=NULL)
{
if(leaf==1&&n->start!=-1)
printf(" [%d]\n",n->suffixIndex);
//Current node is not a leaf as it has outgoing 
//edges from it. 
leaf=0;
setSuffixIndexByDFS(n->children[i],
labelHeight+edgeLength(n->children[i]));
}
}
if(leaf==1)
{
n->suffixIndex=size-labelHeight;
printf(" [%d]\n",n->suffixIndex);
}
}
voidfreeSuffixTreeByPostOrder(Node*n)
{
if(n==NULL)
return;
inti;
for(i=0;i<MAX_CHAR;i++)
{
if(n->children[i]!=NULL)
{
freeSuffixTreeByPostOrder(n->children[i]);
}
}
if(n->suffixIndex==-1)
free(n->end);
free(n);
}
/*Build the suffix tree and print the edge labels along with 
suffixIndex. suffixIndex for leaf edges will be >= 0 and 
for non-leaf edges will be -1*/
voidbuildSuffixTree()
{
size=strlen(text);
inti;
rootEnd=(int*)malloc(sizeof(int));
*rootEnd=-1;
/*Root is a special node with start and end indices as -1, 
 as it has no parent from where an edge comes to root*/
root=newNode(-1,rootEnd);
activeNode=root;//First activeNode will be root 
for(i=0;i<size;i++)
extendSuffixTree(i);
intlabelHeight=0;
setSuffixIndexByDFS(root,labelHeight);
//Free the dynamically allocated memory 
freeSuffixTreeByPostOrder(root);
}
// driver program to test above functions 
intmain(intargc,char*argv[])
{
strcpy(text,"abbc");buildSuffixTree();
printf("Number of nodes in suffix tree are %d\n",count);
return0;
}
Java
class SuffixTreeNode{
SuffixTreeNode[]children;
SuffixTreeNodesuffixLink;
intstart;
int[]end;
intsuffixIndex;
publicSuffixTreeNode()
{
this.children
=newSuffixTreeNode[256];// Assuming ASCII
// characters
this.suffixLink=null;
this.start=0;
this.end=newint[1];
this.suffixIndex=-1;
}
}
publicclass SuffixTree{
staticchar[]text;
staticSuffixTreeNoderoot;
staticSuffixTreeNodelastNewNode;
staticSuffixTreeNodeactiveNode;
staticintcount;
staticintactiveEdge=-1;
staticintactiveLength=0;
staticintremainingSuffixCount=0;
staticintleafEnd=-1;
staticint[]rootEnd;
staticint[]splitEnd;
staticintsize=-1;
publicstaticSuffixTreeNodenewNode(intstart,
int[]end)
{
count++;
SuffixTreeNodenode=newSuffixTreeNode();
for(inti=0;i<256;i++){
node.children[i]=null;
}
node.suffixLink=root;
node.start=start;
node.end=end;
node.suffixIndex=-1;
returnnode;
}
publicstaticintedgeLength(SuffixTreeNoden)
{
returnn.end[0]-n.start+1;
}
publicstaticbooleanwalkDown(SuffixTreeNodecurrNode)
{
if(activeLength>=edgeLength(currNode)){
activeEdge
=text[size-remainingSuffixCount+1]
-' ';
activeLength-=edgeLength(currNode);
activeNode=currNode;
returntrue;
}
returnfalse;
}
publicstaticvoidextendSuffixTree(intpos)
{
leafEnd=pos;
remainingSuffixCount++;
lastNewNode=null;
while(remainingSuffixCount>0){
if(activeLength==0){
activeEdge=text[pos]-' ';
}
if(activeNode.children[activeEdge]==null){
activeNode.children[activeEdge]
=newNode(pos,newint[]{leafEnd});
if(lastNewNode!=null){
lastNewNode.suffixLink=activeNode;
lastNewNode=null;
}
}
else{
SuffixTreeNodenext
=activeNode.children[activeEdge];
if(walkDown(next)){
continue;
}
if(text[next.start+activeLength]
==text[pos]){
if(lastNewNode!=null
&&activeNode!=root){
lastNewNode.suffixLink=activeNode;
lastNewNode=null;
}
activeLength++;
break;
}
splitEnd=newint[]{next.start
+activeLength-1};
SuffixTreeNodesplit
=newNode(next.start,splitEnd);
activeNode.children[activeEdge]=split;
split.children[text[pos]-' ']
=newNode(pos,newint[]{leafEnd});
next.start+=activeLength;
split.children[activeEdge]=next;
if(lastNewNode!=null){
lastNewNode.suffixLink=split;
}
lastNewNode=split;
}
remainingSuffixCount--;
if(activeNode==root&&activeLength>0){
activeLength--;
activeEdge
=text[pos-remainingSuffixCount+1]
-' ';
}
elseif(activeNode!=root){
activeNode=activeNode.suffixLink;
}
}
}
publicstaticvoidprint(inti,intj)
{
for(intk=i;k<=j;k++){
System.out.print(text[k]);
}
}
publicstaticvoidsetSuffixIndexByDFS(SuffixTreeNoden,
intlabelHeight)
{
if(n==null)
return;
if(n.start!=-1){
print(n.start,n.end[0]);
}
intleaf=1;
for(inti=0;i<256;i++){
if(n.children[i]!=null){
if(leaf==1&&n.start!=-1){
System.out.println(" ["+n.suffixIndex
+"]");
}
leaf=0;
setSuffixIndexByDFS(
n.children[i],
labelHeight
+edgeLength(n.children[i]));
}
}
if(leaf==1){
n.suffixIndex=size-labelHeight;
System.out.println(" ["+n.suffixIndex+"]");
}
}
publicstaticvoid
freeSuffixTreeByPostOrder(SuffixTreeNoden)
{
if(n==null)
return;
for(inti=0;i<256;i++){
if(n.children[i]!=null){
freeSuffixTreeByPostOrder(n.children[i]);
}
}
if(n.suffixIndex==-1){
n.end=null;
}
}
publicstaticvoidbuildSuffixTree()
{
size=text.length;
rootEnd=newint[1];
rootEnd[0]=-1;
root=newNode(-1,rootEnd);
activeNode=root;
for(inti=0;i<size;i++){
extendSuffixTree(i);
}
intlabelHeight=0;
setSuffixIndexByDFS(root,labelHeight);
freeSuffixTreeByPostOrder(root);
}
publicstaticvoidmain(String[]args)
{
text="abbc".toCharArray();
buildSuffixTree();
System.out.println(
"Number of nodes in suffix tree are "+count);
}
}
Python
class SuffixTreeNode:
 def __init__(self):
 # Initialize children list to store child nodes for each ASCII character
 self.children = [None] * 256 # Assuming ASCII characters
 # Suffix link for suffix tree construction
 self.suffix_link = None
 # Start index of the substring represented by the edge leading to this node
 self.start = 0
 # End index (as a list to facilitate updates) of the substring represented by the edge leading to this node
 self.end = [0]
 # Index of the suffix represented by the path from root to this node
 self.suffix_index = -1
# Function to create a new suffix tree node
def new_node(start, end):
 global count
 count += 1
 node = SuffixTreeNode()
 # Set suffix link to root initially
 node.suffix_link = root
 node.start = start
 node.end = end
 node.suffix_index = -1
 return node
# Function to calculate the length of an edge represented by a node
def edge_length(n):
 return n.end[0] - n.start + 1
# Function to handle the walk down in suffix tree construction
def walk_down(curr_node):
 global active_length, active_edge, remaining_suffix_count
 if active_length >= edge_length(curr_node):
 # Update active edge and active length to walk down the tree
 active_edge = ord(text[size - remaining_suffix_count + 1]) - ord(' ')
 active_length -= edge_length(curr_node)
 active_node = curr_node
 return True
 return False
# Function to extend the suffix tree for a given position in the text
def extend_suffix_tree(pos):
 global leaf_end, remaining_suffix_count, last_new_node, active_node, active_length, active_edge
 leaf_end = pos
 remaining_suffix_count += 1
 last_new_node = None
 while remaining_suffix_count > 0:
 if active_length == 0:
 # If active length is zero, set active edge for the current position
 active_edge = ord(text[pos]) - ord(' ')
 if not active_node.children[active_edge]:
 # If active edge has no child, create a new node
 active_node.children[active_edge] = new_node(pos, [leaf_end])
 if last_new_node:
 # If there was a previously created node, update its suffix link
 last_new_node.suffix_link = active_node
 last_new_node = None
 else:
 next_node = active_node.children[active_edge]
 if walk_down(next_node):
 continue
 if text[next_node.start + active_length] == text[pos]:
 if last_new_node and active_node != root:
 last_new_node.suffix_link = active_node
 last_new_node = None
 active_length += 1
 break
 split_end = [next_node.start + active_length - 1]
 split_node = new_node(next_node.start, split_end)
 active_node.children[active_edge] = split_node
 split_node.children[ord(text[pos]) - ord(' ')] = new_node(pos, [leaf_end])
 next_node.start += active_length
 split_node.children[active_edge] = next_node
 if last_new_node:
 last_new_node.suffix_link = split_node
 last_new_node = split_node
 remaining_suffix_count -= 1
 if active_node == root and active_length > 0:
 active_length -= 1
 active_edge = ord(text[pos - remaining_suffix_count + 1]) - ord(' ')
 elif active_node != root:
 active_node = active_node.suffix_link
# Function to print the substring of the text given its start and end indices
def print_string(i, j):
 output = ""
 for k in range(i, j + 1):
 output += text[k]
 print(output)
# Function to set suffix indices using depth-first search (DFS)
def set_suffix_index_by_dfs(n, label_height):
 if not n:
 return
 if n.start != -1:
 # Print the substring represented by the edge leading to this node
 print_string(n.start, n.end[0])
 leaf = 1
 for i in range(256):
 if n.children[i]:
 if leaf == 1 and n.start != -1:
 # If this node has children and it's not a leaf node, print its suffix index
 print(" [" + str(n.suffix_index) + "]")
 leaf = 0
 set_suffix_index_by_dfs(
 n.children[i],
 label_height + edge_length(n.children[i]))
 if leaf == 1:
 # If this is a leaf node, set its suffix index
 n.suffix_index = size - label_height
 print(" [" + str(n.suffix_index) + "]")
# Function to free the memory allocated for the suffix tree using post-order traversal
def free_suffix_tree_by_post_order(n):
 if not n:
 return
 for i in range(256):
 if n.children[i]:
 free_suffix_tree_by_post_order(n.children[i])
 if n.suffix_index == -1:
 # If this node doesn't represent any suffix, free its memory
 n.end = None
# Function to build the suffix tree for the given text
def build_suffix_tree():
 global size, root_end, root, active_node, remaining_suffix_count, active_length, active_edge
 size = len(text)
 root_end = [None]
 root_end[0] = -1
 root = new_node(-1, root_end)
 active_node = root
 remaining_suffix_count = 0
 active_length = 0
 active_edge = -1
 for i in range(size):
 # Extend the suffix tree for each position in the text
 extend_suffix_tree(i)
 label_height = 0
 # Set suffix indices using depth-first search (DFS)
 set_suffix_index_by_dfs(root, label_height)
 # Free the memory allocated for the suffix tree using post-order traversal
 free_suffix_tree_by_post_order(root)
if __name__ == "__main__":
 text = list("abbc")
 root = None
 last_new_node = None
 active_node = None
 count = 0
 active_edge = -1
 active_length = 0
 remaining_suffix_count = 0
 leaf_end = -1
 root_end = None
 split_end = None
 size = -1
 build_suffix_tree()
 print("Number of nodes in suffix tree are", count)
C#
usingSystem;
publicclassSuffixTreeNode{
publicSuffixTreeNode[]Children{get;}
=newSuffixTreeNode[256];// Assuming ASCII characters
publicSuffixTreeNodeSuffixLink
{
get;
set;
}
publicintStart
{
get;
set;
}
publicint[]End
{
get;
set;
}
publicintSuffixIndex
{
get;
set;
}
publicSuffixTreeNode()
{
for(inti=0;i<256;i++){
Children[i]=null;
}
SuffixLink=null;
Start=0;
End=newint[1];
SuffixIndex=-1;
}
}
publicclassSuffixTree{
privatestaticchar[]text;
privatestaticSuffixTreeNoderoot;
privatestaticSuffixTreeNodelastNewNode;
privatestaticSuffixTreeNodeactiveNode;
privatestaticintcount;
privatestaticintactiveEdge=-1;
privatestaticintactiveLength=0;
privatestaticintremainingSuffixCount=0;
privatestaticintleafEnd=-1;
privatestaticint[]rootEnd;
privatestaticint[]splitEnd;
privatestaticintsize=-1;
publicstaticSuffixTreeNodeNewNode(intstart,
int[]end)
{
count++;
varnode
=newSuffixTreeNode{SuffixLink=root,
Start=start,End=end,
SuffixIndex=-1};
returnnode;
}
publicstaticintEdgeLength(SuffixTreeNoden)
{
returnn.End[0]-n.Start+1;
}
publicstaticboolWalkDown(SuffixTreeNodecurrNode)
{
if(activeLength>=EdgeLength(currNode)){
activeEdge
=text[size-remainingSuffixCount+1]
-' ';
activeLength-=EdgeLength(currNode);
activeNode=currNode;
returntrue;
}
returnfalse;
}
publicstaticvoidExtendSuffixTree(intpos)
{
leafEnd=pos;
remainingSuffixCount++;
lastNewNode=null;
while(remainingSuffixCount>0){
if(activeLength==0){
activeEdge=text[pos]-' ';
}
if(activeNode.Children[activeEdge]==null){
activeNode.Children[activeEdge]
=NewNode(pos,newint[]{leafEnd});
if(lastNewNode!=null){
lastNewNode.SuffixLink=activeNode;
lastNewNode=null;
}
}
else{
varnext=activeNode.Children[activeEdge];
if(WalkDown(next)){
continue;
}
if(text[next.Start+activeLength]
==text[pos]){
if(lastNewNode!=null
&&activeNode!=root){
lastNewNode.SuffixLink=activeNode;
lastNewNode=null;
}
activeLength++;
break;
}
splitEnd=newint[]{next.Start
+activeLength-1};
varsplit=NewNode(next.Start,splitEnd);
activeNode.Children[activeEdge]=split;
split.Children[text[pos]-' ']
=NewNode(pos,newint[]{leafEnd});
next.Start+=activeLength;
split.Children[text[next.Start]-' ']
=next;
if(lastNewNode!=null){
lastNewNode.SuffixLink=split;
}
lastNewNode=split;
}
remainingSuffixCount--;
if(activeNode==root&&activeLength>0){
activeLength--;
activeEdge
=text[pos-remainingSuffixCount+1]
-' ';
}
elseif(activeNode!=root){
activeNode=activeNode.SuffixLink;
}
}
}
publicstaticvoidPrint(inti,intj)
{
for(intk=i;k<=j;k++){
Console.Write(text[k]);
}
}
publicstaticvoidSetSuffixIndexByDFS(SuffixTreeNoden,
intlabelHeight)
{
if(n==null)
return;
if(n.Start!=-1){
Print(n.Start,n.End[0]);
}
intleaf=1;
for(inti=0;i<256;i++){
if(n.Children[i]!=null){
if(leaf==1&&n.Start!=-1){
Console.WriteLine(" ["+n.SuffixIndex
+"]");
}
leaf=0;
SetSuffixIndexByDFS(
n.Children[i],
labelHeight
+EdgeLength(n.Children[i]));
}
}
if(leaf==1){
n.SuffixIndex=size-labelHeight;
Console.WriteLine(" ["+n.SuffixIndex+"]");
}
}
publicstaticvoid
FreeSuffixTreeByPostOrder(SuffixTreeNoden)
{
if(n==null)
return;
for(inti=0;i<256;i++){
if(n.Children[i]!=null){
FreeSuffixTreeByPostOrder(n.Children[i]);
}
}
if(n.SuffixIndex==-1){
n.End=null;
}
}
publicstaticvoidBuildSuffixTree()
{
size=text.Length;
rootEnd=newint[1];
rootEnd[0]=-1;
root=NewNode(-1,rootEnd);
activeNode=root;
for(inti=0;i<size;i++){
ExtendSuffixTree(i);
}
intlabelHeight=0;
SetSuffixIndexByDFS(root,labelHeight);
FreeSuffixTreeByPostOrder(root);
}
publicstaticvoidMain(string[]args)
{
text="abbc".ToCharArray();
BuildSuffixTree();
Console.WriteLine(
"Number of nodes in suffix tree are "+count);
}
}
JavaScript
constMAX_CHAR=256;
classSuffixTreeNode{
constructor(){
this.children=newArray(MAX_CHAR).fill(null);
this.suffixLink=null;
this.start=0;
this.end=null;
this.suffixIndex=-1;
}
}
lettext="";
letroot=null;
letlastNewNode=null;
letactiveNode=null;
letcount=0;
letactiveEdge=-1;
letactiveLength=0;
letremainingSuffixCount=0;
letleafEnd=-1;
letrootEnd=null;
letsplitEnd=null;
letsize=-1;
// Function to create a new node in the suffix tree
constnewNode=(start,end)=>{
count++;
constnode=newSuffixTreeNode();
for(leti=0;i<MAX_CHAR;i++)
node.children[i]=null;
node.suffixLink=root;
node.start=start;
node.end=end;
node.suffixIndex=-1;
returnnode;
};
// Function to calculate the length of an edge
constedgeLength=(n)=>{
returnn.end-n.start+1;
};
// Function to perform walk down in the tree
constwalkDown=(currNode)=>{
if(activeLength>=edgeLength(currNode)){
activeEdge=text.charCodeAt(activeEdge+edgeLength(currNode))-' '.charCodeAt();
activeLength-=edgeLength(currNode);
activeNode=currNode;
returntrue;
}
returnfalse;
};
// Function to extend the suffix tree
constextendSuffixTree=(pos)=>{
leafEnd=pos;
remainingSuffixCount++;
lastNewNode=null;
while(remainingSuffixCount>0){
if(activeLength===0){
activeEdge=text.charCodeAt(pos)-' '.charCodeAt();
}
if(activeNode.children[activeEdge]===null){
activeNode.children[activeEdge]=newNode(pos,leafEnd);
if(lastNewNode!==null){
lastNewNode.suffixLink=activeNode;
lastNewNode=null;
}
}else{
constnext=activeNode.children[activeEdge];
if(walkDown(next)){
continue;
}
if(text[next.start+activeLength]===text[pos]){
if(lastNewNode!==null&&activeNode!==root){
lastNewNode.suffixLink=activeNode;
lastNewNode=null;
}
activeLength++;
break;
}
splitEnd=next.start+activeLength-1;
constsplit=newNode(next.start,splitEnd);
activeNode.children[activeEdge]=split;
split.children[text.charCodeAt(pos)-' '.charCodeAt()]=newNode(pos,leafEnd);
next.start+=activeLength;
split.children[activeEdge]=next;
if(lastNewNode!==null){
lastNewNode.suffixLink=split;
}
lastNewNode=split;
}
remainingSuffixCount--;
if(activeNode===root&&activeLength>0){
activeLength--;
activeEdge=text.charCodeAt(pos-remainingSuffixCount+1)-' '.charCodeAt();
}elseif(activeNode!==root){
activeNode=activeNode.suffixLink;
}
}
};
// Function to print characters from index i to j
constprint=(i,j)=>{
for(letk=i;k<=j;k++){
process.stdout.write(text[k]);
}
};
// Function to set suffix index by DFS traversal
constsetSuffixIndexByDFS=(n,labelHeight)=>{
if(n===null)return;
if(n.start!==-1){
print(n.start,n.end);
}
letleaf=1;
for(leti=0;i<MAX_CHAR;i++){
if(n.children[i]!==null){
if(leaf===1&&n.start!==-1){
console.log(` [${n.suffixIndex}]`);
}
leaf=0;
setSuffixIndexByDFS(n.children[i],labelHeight+edgeLength(n.children[i]));
}
}
if(leaf===1){
n.suffixIndex=size-labelHeight;
console.log(` [${n.suffixIndex}]`);
}
};
// Function to free memory in post-order traversal
constfreeSuffixTreeByPostOrder=(n)=>{
if(n===null)return;
for(leti=0;i<MAX_CHAR;i++){
if(n.children[i]!==null){
freeSuffixTreeByPostOrder(n.children[i]);
}
}
if(n.suffixIndex===-1){
deleten.end;
}
deleten;
};
// Function to build the suffix tree
constbuildSuffixTree=()=>{
size=text.length;
rootEnd=-1;
root=newNode(-1,rootEnd);
activeNode=root;
for(leti=0;i<size;i++){
extendSuffixTree(i);
}
letlabelHeight=0;
setSuffixIndexByDFS(root,labelHeight);
freeSuffixTreeByPostOrder(root);
};
// Main function
constmain=()=>{
text="abbc";
buildSuffixTree();
console.log(`Number of nodes in suffix tree are ${count}`);
};
main();

Output
abbc [0]
b [-1]
bc [1]
c [2]
c [3]
Number of nodes in suffix tree are 6

Output (Each edge of Tree, along with suffix index of child node on edge, is printed in DFS order. To understand the output better, match it with the last figure no 43 in previous Part 5 article):

Now we are able to build suffix tree in linear time, we can solve many string problem in efficient way:

The above basic problems can be solved by DFS traversal on suffix tree.
We will soon post articles on above problems and others like below:

And More .
Test you understanding?

  1. Draw suffix tree (with proper suffix link, suffix indices) for string "AABAACAADAABAAABAA$" on paper and see if that matches with code output.
  2. Every extension must follow one of the three rules: Rule 1, Rule 2 and Rule 3.
    Following are the rules applied on five consecutive extensions in some Phase i (i > 5), which ones are valid:
    A) Rule 1, Rule 2, Rule 2, Rule 3, Rule 3
    B) Rule 1, Rule 2, Rule 2, Rule 3, Rule 2
    C) Rule 2, Rule 1, Rule 1, Rule 3, Rule 3
    D) Rule 1, Rule 1, Rule 1, Rule 1, Rule 1
    E) Rule 2, Rule 2, Rule 2, Rule 2, Rule 2
    F) Rule 3, Rule 3, Rule 3, Rule 3, Rule 3
  3. What are the valid sequences in above for Phase 5
  4. Every internal node MUST have it's suffix link set to another node (internal or root). Can a newly created node point to already existing internal node or not ? Can it happen that a new node created in extension j, may not get it's right suffix link in next extension j+1 and get the right one in later extensions like j+2, j+3 etc ?
  5. Try solving the basic problems discussed above.

We have published following articles on suffix tree applications:


K

kartik
Improve

K

kartik
Improve
Article Tags :
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

AltStyle によって変換されたページ (->オリジナル) /