Trie Data Structure in Java
The following article provides an outline for Trie Data Structure in Java. Basically, data structure plays a very important part in computer programming and also, we must know when and why we use different types of data structure in computer programming. Normally trie is a discrete data structure, and this is not familiar, or we can say that this is not a widely used data structure but this used in the typical algorithm, a trie is also known as a digital tree; it also has another name that is radix or prefix.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Using a trie data structure, we search the element by prefixes in a well-structured tree with a key, and it is advantageous to store the strings. Moreover, we can perform the different operation trie data structure such as insertion, deletion and searching.
Syntax of Trie Data Structure in Java
Given below is the syntax mentioned:
public void insert_node(specified string of word){ TrieNode present = rootNode; For (char i: word.toCharArray()){ Present = present.getChildren().computeIfAbsent(I, c->new TrieNode()); } Present.setEndOfWord(true) }
Explanation:
By using the above syntax, we try to insert elements into the trie data structure; for that, we need to follow the following steps as follows:
- First, we need to set the present node as a root node for insertion operation.
- After that, we need to set the present character as the first character of the word.
- If a present node exists in the digital tree, then reference to the present character, and if a present node does not exist, we need to create the new node.
- Finally, we can use the Trie key for digital traversing.
Similarly, we can write syntax for delete and search operations.
How does Trie Data Structure work in Java?
Given below shows how trie data structure works in java:
Normally we can perform 3 different operations in a trie data structure as follows:
1. Insert Element Operation
We already explain how insertion operation works in java on the above point. The complexity of insertion operation is O (n), where n represents the size of the key.
2. Finding Element Operation
After insertion operation, we can perform the search or find operation on trie data structure by using the following algorithm as follows.
Code:
public void find_node(specified string of word){ TrieNode present = rootNode; For (char j = 0; j < word.length(); j++){ char c = word.charAt(j); TrieNode node = present.getChildren().get(c); If (node = = null){ return false; } Present = node; } return present.isEndOfWord(); }
Explanation:
Now follow the following steps for the search element in a trie data structure as follows:
- First, get the child node from the root.
- After we need to iterate each and every character in the string.
- Now check whether that specified character is present, or we can say it is part of the sub trie; if the specified character is not a part of sub trie, then return the false and exit.
- Repeat the second and third steps until there is no character present in the string.
- The complexity of insertion operation is O (n), where n represents the size of the key.
3. Delete Element Operation
Besides insertion operation and find the element; clearly, we likewise should have the option to delete operation, so we need to follow the following steps as follows.
- Check whether the specified element is as of now part of the trie.
- In the event that the element is found, eliminate it from the trie.
- The intricacy of this calculation is O(n), where n addresses the length of the key.
Example of Trie Data Structure in Java
Given below is the example of Trie Data Structure in Java:
Code:
import java.util.ArrayList; import java.util.Collections; import java.util.List; // created class to store node into the trie data structure class trie_data { // Define the size of alphabet size private static final int CHAR_AlPHA_SIZE = 26; private boolean isLeaf; private List<trie_data> child = null; // Created Constructor of class trie_data() { isLeaf = false; child = new ArrayList<>(Collections.nCopies(CHAR_AlPHA_SIZE, null)); } // function for insertion operation public void trie_insert(String id) { System.out.println("We inserted new element into the data structure \"" + id + "\""); // Staritng from the parent node that is root node trie_data present = this; for (char ch: id.toCharArray()) { // if node is not exist then create new node in trie if (present.child.get(ch - 'a') == null) { present.child.set(ch - 'a', new trie_data()); } // visit next node present = present.child.get(ch - 'a'); } // mark present as leaf node present.isLeaf = true; } // search function to search element into trie data structure // if key value is not present then it return the false public boolean trie_search(String id) { System.out.print("We searched element\"" + id + "\" : "); trie_data present = this; for (char ch: id.toCharArray()) { // visit next node present = present.child.get(ch - 'a'); if (present == null) { return false; } } return present.isLeaf; } } class Main { public static void main (String[] args) { // construct a new Trie node trie_data head = new trie_data(); head.trie_insert("the"); head.trie_insert("they"); head.trie_insert("final"); System.out.println(head.trie_search("the")); // true System.out.println(head.trie_search("they")); // true System.out.println(head.trie_search("final")); // true System.out.println(head.trie_search("Sample")); // false head.trie_insert("Sample"); System.out.println(head.trie_search("the")); // true System.out.println(head.trie_search("they")); // true System.out.println(head.trie_search("final")); // true System.out.println(head.trie_search("Sample")); // true } }
Explanation:
- In the above example, we try to implement the trie data structure in java, here first we created a class to store the node into the trie data structure. Then, we defined the alphabet size by using CHAR_AlPHA_SIZE. Then, we created a constructor for the class.
- There is a function for insertion operation ‘trie_insert’ () as well as for searching elements from the trie data structure as shown in the above program. At the end of the program, we just call the insert and search function with different values that we need to insert and search in the trie data structure.
Output:
Conclusion
From the above article, we saw the basic syntax of Trie data structure, and we also saw different examples of Trie data structure. From this article, we saw how and when we use the Trie data structure in Java.
The above is the detailed content of Trie Data Structure in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
