// 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;
}
}
|