Algorithm
-
Node Class:
- Define a class
TreeNode
with fields for data, left child (left
), and right child (right
).
- Define a class
-
Binary Tree Class:
- Define a class
BinaryTree
with a root node as an instance variable.
- Define a class
-
Insertion Operation:
- Create a method
insert
in theBinaryTree
class. - Inside
insert
, implement a recursive methodinsertRecursive
that compares the data with the current node and inserts accordingly.
- Create a method
-
In-Order Traversal:
- Implement a method
inOrderTraversal
in theBinaryTree
class. - Inside
inOrderTraversal
, define a recursive method that performs in-order traversal: left subtree, current node, right subtree.
- Implement a method
-
Pre-Order Traversal:
- Implement a method
preOrderTraversal
in theBinaryTree
class. - Inside
preOrderTraversal
, define a recursive method that performs pre-order traversal: current node, left subtree, right subtree.
- Implement a method
-
Post-Order Traversal:
- Implement a method
postOrderTraversal
in theBinaryTree
class. - Inside
postOrderTraversal
, define a recursive method that performs post-order traversal: left subtree, right subtree, current node.
- Implement a method
-
Example Usage:
- Create an instance of the
BinaryTree
class. - Insert nodes using the
insert
method. - Traverse the tree using the
inOrderTraversal
,preOrderTraversal
, andpostOrderTraversal
methods.
- Create an instance of the
This algorithmic list provides a basic structure for implementing a binary tree in Java.
Code Examples
#1 Code Example with Java Programming
Code -
Java Programming
// class to create nodes
class Node {
int key;
Node left, right;
public Node(int item) {
key = item;
left = right = null;
}
}
class BinaryTree {
Node root;
// Traverse tree
public void traverseTree(Node node) {
if (node != null) {
traverseTree(node.left);
System.out.print(" " + node.key);
traverseTree(node.right);
}
}
public static void main(String[] args) {
// create an object of BinaryTree
BinaryTree tree = new BinaryTree();
// create nodes of the tree
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
System.out.print("\nBinary Tree: ");
tree.traverseTree(tree.root);
}
}
Copy The Code &
Try With Live Editor
Output
Binary Tree: 4 2 1 3
Demonstration
Java Programing Example to Implement Binary Tree Data Structure-DevsEnv