// file: BTree.java // The next node is inserted at the 'right most' location, // that is, the tree is always a full binary tree. // dec-06-1998 class BTree { private BinNode root; private BinNode curr; public BTree() { root = null; curr = root; } // BTree public void insert(Object it) // insert 'it' as child of 'curr' // if 'curr' is full (i.e. has both children // go to its sibling { BinNodePtr newNode = new BinNodePtr(it); if (root == null) // brand new { root = newNode; curr = root; } else { if (curr.left() == null) curr.setLeft(newNode); else if (curr.right() == null) { curr.setRight(newNode); // after this insertion, we have to repoint the 'curr' if (curr == root) // easy curr = curr.left(); else curr = rightSibling(); } } // else } // insert private BinNode rightSibling() { LQueue queue = new LQueue(); BinNode help = root; queue.enqueue(help); while (queue.isEmpty() == false && help != curr) { help = (BinNode)queue.dequeue(); if (help.left() != null) queue.enqueue(help.left()); if (help.right() != null) queue.enqueue(help.right()); } if (help == curr) return (BinNode)queue.dequeue(); else return null; // this should neven happen } // rightSibling public void print() // print in pre-order { preorder(root); } private void preorder(BinNode p) { if (p == null) return; System.out.print((String)p.element() + " "); preorder(p.left()); preorder(p.right()); } } // BTree