Java Tree
In Java, a tree is a commonly used data structure that is hierarchical and consists of nodes. Each node has a value and zero or more child nodes. Trees are used in various applications and algorithms, including binary search trees, expression trees, and directory structures. Here, I’ll provide a basic example of creating and working with a simple binary tree in Java.
Let’s create a binary tree class with the following structure:
1
/ \
2 3
/ \
4 5
We’ll represent this tree as a set of connected nodes in Java:
class TreeNode {
int data;
TreeNode left;
TreeNode right;
public TreeNode(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTreeExample {
public static void main(String[] args) {
// Create the root node and build the tree
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// Traverse and print the tree using inorder traversal
System.out.println(“Inorder Traversal:”);
inorderTraversal(root);
}
// Inorder traversal (left-root-right) of the tree
public static void inorderTraversal(TreeNode node) {
if (node != null) {
inorderTraversal(node.left);
System.out.print(node.data + " ");
inorderTraversal(node.right);
}
}
}
In this example:
We create a
TreeNode
class to represent each node in the binary tree. Each node has data (an integer value), a left child node, and a right child node.In the
main
method, we create the root node with a value of 1 and build the tree by connecting child nodes accordingly.We then perform an inorder traversal of the tree to print its contents. In inorder traversal, we visit the left subtree, the root, and the right subtree.
When you run the program, it will print the following output, demonstrating the inorder traversal of the binary tree:
Inorder Traversal:
4 2 5 1 3
This is a basic example of a binary tree in Java. Depending on your requirements, you can create and manipulate various types of trees, such as binary search trees, AVL trees, or custom tree structures to suit your application needs.
Demo Day 1 Video:
Conclusion:
Unogeeks is the No.1 Training Institute for Java Training. Anyone Disagree? Please drop in a comment
You can check out our other latest blogs on Java Training here – Java Blogs
You can check out our Best in Class Java Training details here – Java Training
Follow & Connect with us:
———————————-
For Training inquiries:
Call/Whatsapp: +91 73960 33555
Mail us at: info@unogeeks.com
Our Website ➜ https://unogeeks.com
Follow us:
Instagram: https://www.instagram.com/unogeeks
Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute
Twitter: https://twitter.com/unogeeks