Building a Binary Tree


Unlike other data structures, Java doesn’t provide a built-in class for trees. This example builds a binary tree with at most 7 nodes from the root and level-by-level. The output (traverseTree) uses the inorder traversing.

BinaryTree.java (building a binary tree)
// Java program to build a binary tree
class BinaryTree {
  Node root;

  // The driver method
  public static void main( String[ ] args ) {
    String[ ] node = { null, null, null, null, null, null, null };
    
    for ( int i = 0; i < args.length; i++ )  node[i] = args[i];

    // Fill in the binary tree level-by-level and from the top.
    BinaryTree tree = new BinaryTree( );
    if ( node[0] != null )
      tree.root             = new Node( node[0] );
    if ( node[1] != null )
      tree.root.left        = new Node( node[1] );
    if ( node[2] != null )
      tree.root.right       = new Node( node[2] );
    if ( node[3] != null )
      tree.root.left.left   = new Node( node[3] );
    if ( node[4] != null )
      tree.root.left.right  = new Node( node[4] );
    if ( node[5] != null )
      tree.root.right.left  = new Node( node[5] );
    if ( node[6] != null )
      tree.root.right.right = new Node( node[6] );

    tree.traverseTree( tree.root );
  }

  // Traverse tree inorderly.
  public void traverseTree( Node node ) {
    if ( node != null ) {
      traverseTree( node.left );
      System.out.print( " " + node.key );
      traverseTree( node.right );
    }
  }
}
// Class to create nodes
class Node {
  String key;
  Node   left, right;

  public Node( String item ) {
    key  = item;
    left = right = null;
  }
}

  shell> java BinaryTree  (a maximum of 7 integers to be inserted level-by-level)

  Output: (printing the tree inorderly)

        Result:




      “The past has no power over the present moment.”    
      ― Eckhart Tolle