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.

162 Chap. 5 Binary Trees205040 7520 <strong>to</strong> 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.fall within a given range of values. Fortunately, it requires only a simple localcalculation <strong>to</strong> determine which child(ren) <strong>to</strong> visit.A more difficult situation is illustrated by the following problem. Given anarbitrary binary tree we wish <strong>to</strong> 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 greaterthan the value of A? (This happens <strong>to</strong> be the definition for a binary search tree,described in Section 5.4.) Unfortunately, <strong>to</strong> make this decision we need <strong>to</strong> knowsome context that is not available just by looking at the node’s parent or children.As shown by Figure 5.6, it is not enough <strong>to</strong> verify that A’s left child has a valueless than that of A, <strong>and</strong> that A’s right child has a greater value. Nor is it enough <strong>to</strong>verify that A has a value consistent with that of its parent. In fact, we need <strong>to</strong> knowinformation about what range of values is legal for a given node. That informationmight come from any ances<strong>to</strong>r for the node. Thus, relevant range information mustbe passed down the tree. We can implement this function as follows.boolean checkBST(BSTNode root,Integer low, Integer high) {if (root == null) return true; // Empty subtreeInteger rootkey = root.key();if ((rootkey < low) || (rootkey > high))return false; // Out of rangeif (!checkBST(root.left(), low, rootkey))return false; // Left side failedreturn checkBST(root.right(), rootkey, high);}5.3 Binary Tree Node ImplementationsIn this section we will examine ways <strong>to</strong> implement binary tree nodes. We begin withsome options for pointer-based binary tree node implementations. Then comes a

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

Saved successfully!

Ooh no, something went wrong!