CSC 103 Lecture Notes Week 4
More on Trees, Particularly Traversal
public String traversePreorder(BinaryTreeNode t) { if (t == null) return ""; return t.value.toString() + " " + traversePreorder(t.left) + traversePreorder(t.right); }
public String traverseWithNestedLoop() { String result = ""; // Return result BinaryTreeNode nodeI, nodeJ; // Traversal nodes /* * Traverse the tree with an outer loop that visits to the left and an * inner loop that visits to the right. */ for (nodeI = root; nodeI != null; nodeI = nodeI.left) { for (nodeJ = nodeI; nodeJ != null; nodeJ = nodeJ.right) { result = result + nodeJ.value.toString() + " "; } } return result; }
public String traverseWithStack() { String result = ""; // Return result BinaryTreeNode current; // Current node of traversal boolean done = false; // Termination condition /* * Start the traversal at the root of the tree. */ current = root; /* * Traverse the tree by going off to the left, while saving right * subtrees on a stack. The stack gets checked when we run off the * left end. The traversal continues while there are left nodes to * visit, and the right-node stack is not empty. */ while (!done) { /* * If the current node being visited is not null, visit its value * by concatenating it onto the output result. Push the right * subtree onto the stack, thereby saving it until we're done going * left. Then make current the left subtree and continue the * traversal. */ if (current != null) { result = result + current.value.toString() + " "; push(current.right); current = current.left; } /* * If the current node is null, then check the stack of postponed * right subtrees. If the stack is empty, we're done with the * traversal. Otherwise, pop the stack into the current node and * continue the traversal. */ else { if (emptyStack()) { done = true; } else { current = pop(); } } } return result; }