12.07.2015 Views

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

A Practical Introduction to Data Structures and Algorithm Analysis

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Sec. 6.3 General Tree Implementations 217RA BC D E FIndex Val Par01234567RACBDFE0101311 32 4 65Figure 6.9 The “list of children” implementation for general trees. The columnof numbers <strong>to</strong> the left of the node array labels the array indices. The columnlabeled “Val” s<strong>to</strong>res node values. The column labeled “Par” s<strong>to</strong>res pointers <strong>to</strong> theparents. For clarity, these pointers are shown as array indices. The last columns<strong>to</strong>res pointers <strong>to</strong> the linked list of children for each internal node. Each elemen<strong>to</strong>n the linked list s<strong>to</strong>res a pointer <strong>to</strong> one of the node’s children (shown as the arrayindex of the target node).6.3.1 List of ChildrenOur first attempt <strong>to</strong> create a general tree implementation is called the “list of children”implementation for general trees. It simply s<strong>to</strong>res with each internal node alinked list of its children, in order from left <strong>to</strong> right. This is illustrated by Figure 6.9.The “list of children” implementation s<strong>to</strong>res the tree nodes in an array. Eachnode contains a value, a pointer <strong>to</strong> its parent, <strong>and</strong> a pointer <strong>to</strong> a linked list of thenode’s children, s<strong>to</strong>red from left <strong>to</strong> right. Each list element contains a pointer <strong>to</strong>one child. Thus, the leftmost child of a node can be found directly because it isthe first element in the linked list. However, <strong>to</strong> find the right sibling for a node ismore difficult. Consider the case of a node M <strong>and</strong> its parent P. To find M’s rightsibling, we must move down the child list of P until the linked list element s<strong>to</strong>ringthe pointer <strong>to</strong> M has been found. Going one step further takes us <strong>to</strong> the linked listelement that s<strong>to</strong>res a pointer <strong>to</strong> M’s right sibling. Thus, in the worst case, <strong>to</strong> findM’s right sibling requires that all children of M’s parent be searched.Combining trees using this representation is difficult if each tree is s<strong>to</strong>red in aseparate node array. If the nodes of both trees are s<strong>to</strong>red in a single node array, then

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

Saved successfully!

Ooh no, something went wrong!