// BinaryTree class; stores a binary tree. // Original source: http://www.cs.fiu.edu/~weiss/dsj2/code/BinaryTree.java // Modifications to Weiss's code and comments by DIS // *******************PUBLIC OPERATIONS**************************************** // Various tree traversals, isEmpty, makeEmpty. // Also, the following tricky method: // void merge(Object root,BinaryTree t1,BinaryTree t2 ) -> Construct new tree public class BinaryTree { private BinaryNode root; public BinaryTree( ) { root = null; } public BinaryTree( Object rootItem ) { root = new BinaryNode( rootItem, null, null ); } public void printPreOrder( ) { if( root != null ) root.printPreOrder( ); } public void printInOrder( ) { if( root != null ) root.printInOrder( ); } public void printPostOrder( ) { if( root != null ) root.printPostOrder( ); } public boolean isEmpty( ) { return root == null; } // Merge routine for BinaryTree class. // Forms a new tree from rootItem, t1 and t2. Does not allow t1 and t2 // to be the same. Correctly handles other aliasing conditions. public void merge( Object rootItem, BinaryTree t1, BinaryTree t2 ) { if( t1.root == t2.root && t1.root != null ) { System.err.println( "leftTree==rightTree; merge aborted" ); return; } // Allocate new node root = new BinaryNode( rootItem, t1.root, t2.root ); // Ensure that every node is in one tree if( this != t1 ) t1.root = null; if( this != t2 ) t2.root = null; } public BinaryNode getRoot( ) { return root; } } // Class BinaryTree