Algorithm


  1. Node Class:

    • Define a class TreeNode with fields for data, left child (left), and right child (right).
  2. Binary Tree Class:

    • Define a class BinaryTree with a root node as an instance variable.
  3. Insertion Operation:

    • Create a method insert in the BinaryTree class.
    • Inside insert, implement a recursive method insertRecursive that compares the data with the current node and inserts accordingly.
  4. In-Order Traversal:

    • Implement a method inOrderTraversal in the BinaryTree class.
    • Inside inOrderTraversal, define a recursive method that performs in-order traversal: left subtree, current node, right subtree.
  5. Pre-Order Traversal:

    • Implement a method preOrderTraversal in the BinaryTree class.
    • Inside preOrderTraversal, define a recursive method that performs pre-order traversal: current node, left subtree, right subtree.
  6. Post-Order Traversal:

    • Implement a method postOrderTraversal in the BinaryTree class.
    • Inside postOrderTraversal, define a recursive method that performs post-order traversal: left subtree, right subtree, current node.
  7. Example Usage:

    • Create an instance of the BinaryTree class.
    • Insert nodes using the insert method.
    • Traverse the tree using the inOrderTraversal, preOrderTraversal, and postOrderTraversal methods.

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

x
+
cmd
Binary Tree: 4 2 1 3
Advertisements

Demonstration


Java Programing Example to Implement Binary Tree Data Structure-DevsEnv