Binary Tree Node Class ADT for binary tree
Binary Tree Node Class /** ADT for binary tree nodes */ public interface Bin. Node<E> { /** Return and set the element value */ public E element(); public E set. Element(E v); /** Return the left child */ public Bin. Node<E> left(); /** Return the right child */ public Bin. Node<E> right(); } /** Return true if this is a leaf node */ public boolean is. Leaf(); 1
Traversals (1) Any process for visiting the nodes in some order is called a traversal. Any traversal that lists every node in the tree exactly once is called an enumeration of the tree’s nodes. 2
Traversals (2) • Preorder traversal: Visit each node before visiting its children. • Postorder traversal: Visit each node after visiting its children. • Inorder traversal: Visit the left subtree, then the node, then the right subtree. 3
Traversals (3) /** @param rt The root of the subtree */ void preorder(Bin. Node rt) { if (rt == null) return; // Empty subtree visit(rt); preorder(rt. left()); preorder(rt. right()); } 4
Traversals (3) /** @param rt The root of the subtree */ void preorder(Bin. Node rt) { if (rt == null) return; // Empty subtree visit(rt); preorder(rt. left()); preorder(rt. right()); } // This implementation is void preorder(Bin. Node rt) { visit(rt); if (rt. left() != null) if (rt. right() != null) } error prone // Not so good preorder 2(rt. left()); preorder 2(rt. right()); 5
Recursion Examples 1 int count(Bin. Node rt) { if (rt == null) return 0; return 1 + count(rt. left()) + count(rt. right()); } 6
Recursion Examples 2 boolean check. BST(Bin. Node<Integer> rt, Integer low, Integer high) { if (rt == null) return true; Integer rootkey = rt. key(); if ((rootkey < low) || (rootkey > high)) return false; // Out of range if (!check. BST(rt. left(), low, rootkey)) return false; // Left side failed return check. BST(rt. right(), rootkey, high); } 7
- Slides: 7