search
HomeJavajavaTutorialTree traversal Java

Java tree traversal is defined as an algorithm that is implemented in Java programming language, which comprises of the tree as a data structure and incorporates the fundamental of visiting all nodes of the tree through the implementation of the algorithm. Traversal in computer science data structure terminology denotes that all nodes in the data structure need to be visited in order to complete the bigger task at hand. The components of a tree are root and child nodes, some of which end at that particular node and is named as leaves and the others creating more sub-trees. In this article, we will go through the implementation of tree traversal in Java and look at the different methods through which we can achieve the same.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Syntax

Declaration of class in Java:

class <class name> {
// List the fields (variables) for the class
// Define the methods of the class to perform the specified operations
}</class>

Defining a method in Java:

returnType <method name>() {
// Body of the method that constitutes the steps that will fulfill the assigned task
}</method>

Declaring the node in Java:

Node <variable name> = new Node(" <value>");
Access the left of the node in Java:
<variable name>.left</variable></value></variable>

Access the right of the node in Java:

<variable name>.right</variable>

How to perform Tree traversal in Java?

Before we start discussing the different ways of traversing a tree in Java, we first need to know how a tree is structured because this is one of the essential components in order to build the tree as a class in Java. The tree has nodes, and hence we define a node class. This class will have fields as the data that is representing the data of the node, a left pointer that points to the left of the node, and another pointer that points to the right of the node. All these fields constitute the Node class. Below is a schematic of how a tree looks like:

Tree traversal Java

Once we have defined the tree class that constitutes the nodes and the pointer, it is now time to look at the 3 types of traversals that are implemented in Java and each of them having its own signature of traversal:

1 In-order Traversal

The way this traversal is defined is we visit the elements of the left subtree, followed by the node of the subtree, and then finally traverse the right subtree. The pseudocode is as follows:

  • Recursively call the function by passing the left node till we reach node as null.
  • Display the data
  • Recursively call the function by passing the right node till we reach node as null.

The path of traversal of the In-order algorithm will be: Node 1.1→Node 1→Node 1.2→Root→ Node 2.

2. Pre-order Traversal

The way this traversal is defined is to visit the elements of the root node, traverse the left subtree, and then finally traverse the right subtree. The pseudocode is as follows:

  • Traverse the root node first.
  • Recursively call the function by passing the left node till we reach node as null.
  • Recursively call the function by passing the right node till we reach node as null.

The path of traversal of the pre-order algorithm will be: Root→Node 1→Node 1.1→Node 1.2→ Node 2.

3. Post-order Traversal

The way this traversal is defined is we visit the elements of the left subtree, followed by the right subtree, and then finally traverse the node of the subtree till we reach the base node. The pseudocode is as follows:

  • Recursively call the function by passing the left node till we reach node as null.
  • Recursively call the function by passing the right node till we reach node as null.
  • Display the data

The path of traversal of the post-order algorithm will be: Node 1.1→Node 1.2→ Node 1→Node 2→ Root.

Examples of Tree traversal Java

Given below are the examples of Tree traversal Java:

Tree traversal Java

Example #1

In order traversal using recursion

Syntax

class NodeClass {
int value;
NodeClass left, right;
public NodeClass(int key) {
value = key;
left = right = null;
}
}
class Tree {
NodeClass base;
Tree() {
base = null;
}
void inOrderFunc(NodeClass node) {
if (node == null)
return;
inOrderFunc(node.left);
System.out.print(node.value + "->");
inOrderFunc(node.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.base = new NodeClass(27);
tree.base.left = new NodeClass(9);
tree.base.right = new NodeClass(19);
tree.base.left.left = new NodeClass(91);
tree.base.left.right = new NodeClass(92);
System.out.println("In Order traversal");
tree.inOrderFunc(tree.base);
}
}

Output:

Tree traversal Java

Example #2

Pre-order traversal using recursion

Syntax

class NodeClass {
int item;
NodeClass left, right;
public NodeClass(int key) {
item = key;
left = right = null;
}
}
class Tree {
NodeClass base;
Tree() {
base = null;
}
void preorderFunc(NodeClass node) {
if (node == null)
return;
//First the node:
System.out.print(node.item + "->");
//Recursively look at the left side of the tree
preorderFunc(node.left);
//Recursively look at the right side of the tree
preorderFunc(node.right);
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.base = new NodeClass(27);
tree.base.left = new NodeClass(9);
tree.base.right = new NodeClass(19);
tree.base.left.left = new NodeClass(91);
tree.base.left.right = new NodeClass(92);
// preorderFunc tree traversal
System.out.println("Preorder traversal: ");
tree.preorderFunc(tree.base);
}
}

Output:

Tree traversal Java

Example #3

Postorder traversal through recursion

Syntax

class NodeClass {
int item;
NodeClass left, right;
public NodeClass(int key) {
item = key;
left = right = null;
}
}
class Tree {
NodeClass base;
Tree() {
base = null;
}
void postorderFunc(NodeClass node) {
if (node == null)
return;
postorderFunc(node.left);
postorderFunc(node.right);
System.out.print(node.item + "->");
}
public static void main(String[] args) {
Tree tree = new Tree();
tree.base = new NodeClass(27);
tree.base.left = new NodeClass(9);
tree.base.right = new NodeClass(19);
tree.base.left.left = new NodeClass(91);
tree.base.left.right = new NodeClass(92);
System.out.println("Postorder traversal: ");
tree.postorderFunc(tree.base);
}
}

Output:

Tree traversal Java

Conclusion

This article looked at all the various ways of implementing tree traversal in Java, along with examples from the real world. Readers are encouraged to look at the traversal by adding more nodes into the code and seeing the traversal results!

The above is the detailed content of Tree traversal Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools