COMP 250 Winter 2010
19  binary trees
Feb 19, 2010
Binary Trees
The
order
of a (rooted) tree is the maximum number of children of any node. A tree of order
n
is
called an
n
ary tree. It is very common to use trees of order 2. These are called
binary trees
.
Each node of a binary tree can have two children, called the
left child
and
right child
. The terms
“left” and “right” refer to their relative position when you draw the tree. Here is a typical definition
of a binary tree node.
class BTNode<T>{
T
e;
BTNode<T>
parent;
// optional, analogous to "prev" of linked list
BTNode<T>
left;
BTNode<T>
right;
}
A binary tree is a special case of a tree, so the algorithms we have discussed for computing
the depth or height of a node and for traversing a tree apply to binary trees as well. There is one
more traversal algorithm to be mentioned, which is commonly used for binary trees, called
inorder
traversal
.
inorderTraversal(root){
if (root is not empty){
// base case
inorderTraversal(root.left)
visit root
inorderTraversal(root.right)
}
}
[ASIDE: You could define an inorder traversal for general trees. For example, you could visit the
first child, then visit the root, then visit any remaining children. But such inorder traversals are
typically not used for general trees, though.]
Example
a
/
\
b
c
/ \
/ \
d e
f g
level order: a b c d e f g
preorder:
a b d e c f g
postorder:
d e b f g c a
inorder:
d b e a f c g
1
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
COMP 250 Winter 2010
19  binary trees
Feb 19, 2010
Expression Trees
You are familiar with forming expressions using
operators
This is the end of the preview.
Sign up
to
access the rest of the document.
 Spring '08
 BLANCHETTE
 Computer Science, Tree traversal, Nested set model

Click to edit the document details