03/27/09
18:38:38
1
26
CS 61B: Lecture 26
Monday, March 30, 2009
Today’s reading:
Goodrich & Tamassia, Section 10.1.
Representing Binary Trees

Recall that a binary tree is a rooted tree wherein no node has more than
two children.
Additionally, every child is either a _left_child_ or
a _right_child_ of its parent, even if its parent has only one child.
In the most popular binary tree representation, each tree node has three
references to neighboring tree nodes: a "parent" reference, and "left" and
"right" references for the two children.
(For some algorithms, the "parent"
references are unnecessary.)
Each node also has an "item" reference.
public class BinaryTreeNode {

public class BinaryTree {
Object item;

BinaryTreeNode root;
BinaryTreeNode parent;

int size;
BinaryTreeNode left;

}
BinaryTreeNode right;

public void inorder() {
if (left != null) {
left.inorder();
}
this.visit();
if (right != null) {
right.inorder();
}
}
}
================================================
+ BINARY TREE  
+
=============== 
 
+
+
.root
size7 
+
+
+
 
+
+

+
+
v
BinaryTree object
+
+

+
+
 * 
+
+

 +
+ Root node =>
add

parent
 +
+

 +
+
..

item
 +
+
/\
 +
+
/
^^ \
leftright +
+
v
/
\ v
 +
+
/
\
structure of +
+
 . 
 . 
BinaryTreeNodes +
+


+
+
sub
div
+
+


+
+
>..
..<
+
+
/ /
\ \
+
+
/ /
^
^
\ \
+
+
/ v
v
v
v \
+
+
+
+
+
+
+
+
 . 
 . 
 . 
 . 
+
+




+
+
 6 
 5 
 9 
 3 
+
+




+
+
**
**
**
**
+
+




+
================================================
BINARY SEARCH TREES
===================
An _ordered_dictionary_ is a dictionary in which the keys have a total order,
just like in a heap.
You can insert, find, and remove entries, just as with a
hash table.
But unlike a hash table, you can quickly find the entry with
minimum or maximum key, or the entry nearest another entry in the total order.
An ordered dictionary does anything a dictionary or binary heap can do and
more, albeit more slowly.
The simplest implementation of an ordered dictionary is a binary search tree,
wherein entries are maintained in a (somewhat) sorted order.
18
The _left_subtree_ of a node is the subtree rooted at the
/
\
node’s left child; _right_subtree_ is defined similarly.
12
25
A binary search tree satisfies the _binary_search_tree_
/ \
/ \
_invariant_:
for any node X, every key in the left subtree
4
15
25
30
of X is less than or equal to X’s key, and every key in the
/
/
\
/
right subtree of X is greater than or equal to X’s key.
You
1
13
17
28
can verify this in the search tree at left:
for instance,
\
\
\
the root is 18, its left subtree (rooted at 12) contains
3
14
29
numbers from 1 to 17, and its right subtree (rooted at 25)
contains numbers from 25 to 30.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '01
 Canny
 Data Structures

Click to edit the document details