data structures csci 132, spring 2014 lecture 35 binary trees
DESCRIPTION
Data Structures CSCI 132, Spring 2014 Lecture 35 Binary Trees. Binary Trees. Definition: A binary tree is either empty or it consists of a root together with two binary trees called the left subtree and the right subtree. Examples:. Two node trees. Three node trees. Traversing Binary Trees. - PowerPoint PPT PresentationTRANSCRIPT
1
Data Structures
CSCI 132, Spring 2014Lecture 35Binary Trees
2
Binary TreesDefinition: A binary tree is either empty or it consists of a root together with two binary trees called the left subtree and the right subtree.
Examples:Two node trees
Three node trees
3
Traversing Binary Trees
To traverse a tree, we move through the tree and visit each node one at a time. This can be done in various orders:
preorder: VLR--Visit a node, then visit the left subtree, then visit the right subtree.
inorder: LVR--Visit the left subtree, then visit the node, then visit the right subtree.
postorder: LRV--Visit the left subtree, then visit the right subtree, then visit the node.
4
Tree traversal examples
1
2 3
preorder: 1 2 3inorder: 2 1 3postorder: 2 3 1
1
2
3
4 5
We will work this one out in class.
5
Expression trees
6
Comparison trees for binary search
Binary search of the following list:Amy Ann Dot Eva Guy Jan Jim Jon Kay Kim Ron Roy Tim Tom
Note that inorder traversal gives the list in alphabetical order.
7
Binary_node struct
template <class Entry>struct Binary_node { // data members: Entry data; Binary_node<Entry> *left; Binary_node<Entry> *right; // constructors: Binary_node( ); Binary_node(const Entry &x);};
8
Binary_tree class
template <class Entry>class Binary_tree {public:
// Add methods here.protected:
// Add auxiliary function prototypes here.Binary_node<Entry> *root;
};
9
Binary search tree with pointers
10
Implementation of constructor and empty( ) functions
template <class Entry>Binary_tree<Entry> :: Binary_tree( ){
root = NULL;}
template <class Entry>bool Binary_tree<Entry> :: empty( ) const{
return root == NULL;}
11
In order traversal
template <class Entry>void Binary_tree<Entry> :: inorder(void (*visit)(Entry &)) {
recursive_inorder(root, visit);}
template <class Entry>void Binary_tree<Entry> :: recursive_inorder(Binary_node<Entry> *sub_root,
void (*visit)(Entry &)) {
//We'll work this out in class}
12
Binary_tree specificationtemplate <class Entry>class Binary_tree {public:
Binary_tree( );bool empty( ) const;void preorder(void (*visit)(Entry &));void inorder(void (*visit)(Entry &));void postorder(void (*visit)(Entry &));int size( ) const;void clear( );int height( ) const;void insert(const Entry &);Binary_tree (const Binary_tree<Entry> &original);Binary_tree & operator = (const Binary_tree<Entry> &original);~Binary_tree( );
protected:// Add auxiliary function prototypes here.Binary_node<Entry> *root;
};