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

Create successful ePaper yourself

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

Sec. 5.2 Binary Tree Traversals 153205040 7520 to 40Figure 5.6 To be a binary search tree, the left child of the node with value 40must have a value between 20 <strong>and</strong> 40.Another problem th<strong>at</strong> occurs when recursively processing d<strong>at</strong>a collections iscontrolling which members of the collection will be visited. For example, sometree “traversals” might in fact visit only some tree nodes, while avoiding processingof others. Exercise 5.20 must solve exactly this problem in the context of a binarysearch tree. It must visit only those children of a given node th<strong>at</strong> might possiblyfall within a given range of values. Fortun<strong>at</strong>ely, it requires only a simple localcalcul<strong>at</strong>ion to determine which child(ren) to visit.A more difficult situ<strong>at</strong>ion is illustr<strong>at</strong>ed by the following problem. Given anarbitrary binary tree we wish to determine if, for every node A, are all nodes in A’sleft subtree less than the value of A, <strong>and</strong> are all nodes in A’s right subtree gre<strong>at</strong>erthan the value of A? (This happens to be the definition for a binary search tree,described in Section 5.4.) Unfortun<strong>at</strong>ely, to make this decision we need to knowsome context th<strong>at</strong> is not available just by looking <strong>at</strong> the node’s parent or children.As shown by Figure 5.6, it is not enough to verify th<strong>at</strong> A’s left child has a valueless than th<strong>at</strong> of A, <strong>and</strong> th<strong>at</strong> A’s right child has a gre<strong>at</strong>er value. Nor is it enough toverify th<strong>at</strong> A has a value consistent with th<strong>at</strong> of its parent. In fact, we need to knowinform<strong>at</strong>ion about wh<strong>at</strong> range of values is legal for a given node. Th<strong>at</strong> inform<strong>at</strong>ionmight come from any of the node’s ancestors. Thus, relevant range inform<strong>at</strong>ionmust be passed down the tree. We can implement this function as follows.boolean checkBST(BinNode rt,int low, int high) {if (rt == null) return true; // Empty subtreeint rootkey = rt.element();if ((rootkey < low) || (rootkey > high))return false; // Out of rangeif (!checkBST(rt.left(), low, rootkey))return false; // Left side failedreturn checkBST(rt.right(), rootkey, high);}

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

Saved successfully!

Ooh no, something went wrong!