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.

Sec. 6.1 General Tree Definitions <strong>and</strong> Terminology 197/** General tree node ADT */interface GTNode {public E value();public boolean isLeaf();public GTNode parent();public GTNode leftmostChild();public GTNode rightSibling();public void setValue(E value);public void setParent(GTNode par);public void insertFirst(GTNode n);public void insertNext(GTNode n);public void removeFirst();public void removeNext();}/** General tree ADT */interface GenTree {public void clear(); // Clear the treepublic GTNode root(); // Return the root// Make the tree have a new root, give first child <strong>and</strong> sibpublic void newroot(E value, GTNode first,GTNode sib);public void newleftchild(E value); // Add left child}Figure 6.2 Interfaces for the general tree <strong>and</strong> general tree nodeOne choice would be to provide a function th<strong>at</strong> takes as its parameter the indexfor the desired child. Th<strong>at</strong> combined with a function th<strong>at</strong> returns the number ofchildren for a given node would support the ability to access any node or processall children of a node. Unfortun<strong>at</strong>ely, this view of access tends to bias the choice fornode implement<strong>at</strong>ions in favor of an array-based approach, because these functionsfavor r<strong>and</strong>om access to a list of children. In practice, an implement<strong>at</strong>ion based ona linked list is often preferred.An altern<strong>at</strong>ive is to provide access to the first (or leftmost) child of a node, <strong>and</strong>to provide access to the next (or right) sibling of a node. Figure 6.2 shows classdeclar<strong>at</strong>ions for general trees <strong>and</strong> their nodes. Based on these two access functions,the children of a node can be traversed like a list. Trying to find the next sibling ofthe rightmost sibling would return null.6.1.2 General Tree TraversalsIn Section 5.2, three tree traversals were presented for binary trees: preorder, postorder,<strong>and</strong> inorder. For general trees, preorder <strong>and</strong> postorder traversals are definedwith meanings similar to their binary tree counterparts. Preorder traversal of a generaltree first visits the root of the tree, then performs a preorder traversal of eachsubtree from left to right. A postorder traversal of a general tree performs a postordertraversal of the root’s subtrees from left to right, then visits the root. Inorder

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

Saved successfully!

Ooh no, something went wrong!