11.07.2015 Views

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

Data Structures and Algorithm Analysis - Computer Science at ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

150 Chap. 5 Binary Trees/** ADT for binary tree nodes */public interface BinNode {/** Get <strong>and</strong> set the element value */public E element();public void setElement(E v);}/** @return The left child */public BinNode left();/** @return The right child */public BinNode right();/** @return True if a leaf node, false otherwise */public boolean isLeaf();Figure 5.5 A binary tree node ADT.Example 5.1 The preorder enumer<strong>at</strong>ion for the tree of Figure 5.1 isABDCEGFHI.The first node printed is the root. Then all nodes of the left subtree areprinted (in preorder) before any node of the right subtree.Altern<strong>at</strong>ively, we might wish to visit each node only after we visit its children(<strong>and</strong> their subtrees). For example, this would be necessary if we wish to returnall nodes in the tree to free store. We would like to delete the children of a nodebefore deleting the node itself. But to do th<strong>at</strong> requires th<strong>at</strong> the children’s childrenbe deleted first, <strong>and</strong> so on. This is called a postorder traversal.Example 5.2 The postorder enumer<strong>at</strong>ion for the tree of Figure 5.1 isDBGEHIFCA.An inorder traversal first visits the left child (including its entire subtree), thenvisits the node, <strong>and</strong> finally visits the right child (including its entire subtree). Thebinary search tree of Section 5.4 makes use of this traversal to print all nodes inascending order of value.Example 5.3 The inorder enumer<strong>at</strong>ion for the tree of Figure 5.1 isBDAGECHFI.A traversal routine is n<strong>at</strong>urally written as a recursive function. Its input parameteris a reference to a node which we will call rt because each node can be

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!