CMPSCI 187: Programming With Data Structures

David Mix Barrington

Fall, 2011

Discussion Assignment #10: Navigating Linked Binary Trees

23 November 2011

We've seen four ways to traverse a binary tree: inorder, preorder, postorder, and level order. The first three have elegant recursive definitions, though the fourth does not. In this discussion we will study these four traversals in a different way -- for each one we will write a method that will return the next node in the given order, using the pointers to navigate. This will give us some good experience navigating binary trees.

Our trees may have unary nodes, and we won't be concerned here with their elements, so we will use the following simple class (note that I have added a pointer up to the node's parent):


    public class TreeNode {
       public TreeNode up, left, right;
       public TreeNode ( ) {up = left = right = null;}
       public boolean isLeft( )
          {return (up != null) && (this == up.left);}
       public boolean isRight( )
          {return (up != null) && (this == up.right);}}

    public class BinaryTree {
       public TreeNode root;
       public BinaryTree ( ) {root = null;}}

Our example tree has ten nodes. The root S has children U and P, U has only left child E which has only right child A, P has children R and C, R has children L and I, I has only left child F, and all other nodes are leaves.

Here is code for one of the four methods, for inorder:


    public TreeNode nextIn ( ) {
       if (right != null) { // return inorder-first descendant of right
          TreeNode cur = right;
          while (cur.left != null) cur = cur.left;
          return cur;}
       // find parent of lowest ancestor that is a left child,
       // including this, or null if there is no such ancestor
       TreeNode anc = this;
       while (anc.isRight( )) anc = anc.up;
       return anc.up;}

Exercises:

Warmup: List the ten nodes of the tree described above, in each of the four orders (inorder, preorder, postorder, and level order):

Question 1: Write a method public TreeNode nextPre( ) for the TreeNode class, that returns the next node in preorder, or returns null if the calling node is the last one in the tree.

Question 2: Write a method public TreeNode nextPost( ) for the TreeNode class, that returns the next node in postorder, or returns null if the calling node is the last one in the tree.

Question 3: Write a method public TreeNode nextLevel( ) for the TreeNode class, that returns the next node in level order, or returns null if the calling node is the last one in the tree. I found it useful to also write a method public TreeNode firstDesc (int depth). If the calling node has any descendents at the given depth (that many levels below it), firstDesc returns the leftmost one -- otherwise it returns null. This method is most easily coded recursively.

Last modified 27 November 2011