ADT for binary tree nodes public interface BinNodeltEgt Return and set the element value public E element public E setElementE v Return the left child public BinNodeltEgt left ID: 351307
Download Presentation The PPT/PDF document "1 Binary Tree Node Class" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
1
Binary Tree Node Class
/** ADT for binary tree nodes */
public interface BinNode<E> {
/** Return and set the element value */
public E element();
public E setElement(E v);
/** Return the left child */
public BinNode<E> left();
/** Return the right child */
public BinNode<E> right();
/** Return true if this is a leaf node */
public boolean isLeaf();
}Slide2
2
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.Slide3
3
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.Slide4
4
Traversals (3)
/** @param rt The root of the subtree */
void preorder(BinNode rt)
{
if (rt == null) return; // Empty subtree
visit(rt);
preorder(rt.left());
preorder(rt.right());
}Slide5
5
Traversals (3)
/** @param rt The root of the subtree */
void preorder(BinNode rt)
{
if (rt == null) return; // Empty subtree
visit(rt);
preorder(rt.left());
preorder(rt.right());
}
// This implementation is error prone
void preorder(BinNode rt) // Not so good
{
visit(rt);
if (rt.left() != null) preorder2(rt.left());
if (rt.right() != null) preorder2(rt.right());
}Slide6
6
Recursion Examples 1
int count(BinNode rt) {
if (rt == null) return 0;
return 1 + count(rt.left()) +
count(rt.right());
}Slide7
7
Recursion Examples 2
boolean checkBST(BinNode<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 (!checkBST(rt.left(), low, rootkey))
return false; // Left side failed
return checkBST(rt.right(), rootkey, high);
}