Binary Trees and Binary Search Trees
Binary Trees and Binary Search Trees
Trees
1. Introduction
• So far, ADTs have the following major operations : Insert, Delete, Retrieve
• Terminology
C D
B
H I J K
E F G
O
L M N
• The remaining nodes are partitioned into n >= 0 disjoint sets T1, T2, … ,
Tn, where each of these sets is a tree. T1, T2, …, Tn are called the subtrees
of the root.
• Definition : Nodes that have degree zero are called leaf nodes or terminal
nodes.
• Definition : Nodes that are not leaf nodes are called interior nodes or
nonterminal nodes.
• Definition : The roots of the subtrees of a node X, are called the children of
X. X is the parent of its children.
2
9. Binary Trees and Binary Search Trees
• You may also use the notions of grandchildren, grand parent etc
Example : Siblings
B, C, D
I, J, K
N,O
• Definition : The degree of a tree is the maximum degree of the nodes in the
tree
• Definition : The ancestors of a node are all the nodes along the path from
the root to that node
• Definition : The descendants of a node are all nodes in all the subtrees of the
node
• Property : There is only one path from the root of a tree to every other node
3
9. Binary Trees and Binary Search Trees
• Definition : The level of a node is defined recursively as follows :
• Definition : a full binary tree is a binary tree where all interior nodes have 2
children and all terminal nodes are in the same level. Example : Figure 2.
• Definition : a leftist (rightist) tree is a binary tree where every interior node
has only a left (right) subtree. Example : Figure 3 (Figure 4)
4
9. Binary Trees and Binary Search Trees
• Definition : A balanced binary tree is a binary tree in which the left and
right subtrees of any node have heights that differ by at most 1.
Example : Figure 1 and Figure 2
• Definition : a complete binary tree is a full binary tree except that some of
the rightmost leave may be missing. Example : Figure 1
• Note : A full binary tree is a complete binary tree. A complete binary tree is
balanced tree
• Properties :
5
9. Binary Trees and Binary Search Trees
+postorderTraverse(
in visit: FunctionType)
6
9. Binary Trees and Binary Search Trees
• Example : using the ADT operations to build a binary tree
T1.setRootData(‘B’)
T1.attachLeft(‘D’) A
T1.attachRight(‘E’)
B C
T2.setRootData(‘C’)
T2.attachLeft(‘F’)
T2.attachRight(‘G’) D E F G
T3.setRootData(‘A’)
T3.attachLeftSubtree(T1)
T3.attachRightSubTree(T2)
• There are 3 ways to traverse all the nodes of a binary tree and produce a
listing. Note : Each node only visit once
• Inorder Traversal of T is
an inorder traversal of all nodes in the left subtree of r
r
an inorder traversal of all nodes in the right subtree of r
• Preorder Traversal of T is
r
a preorder traversal of all nodes in the left subtree of r
a preorder traversal of all nodes in the right subtree of r
• Postorder Traversal of T is
a postorder traversal of all nodes in the left subtree of r
a postorder traversal of all nodes in the right subtree of r
r
7
9. Binary Trees and Binary Search Trees
A
• Example :
*
A B
B C c
C D -
D E F
E G a b
G H H
F
8
9. Binary Trees and Binary Search Trees
Initially :
root = -1
free = 0 // use rightChild to point to next free node
Root = 0
Free = 6
Index item leftChild rightChild
0 A 1 2
1 B 3 4
A
2 C 5 -
3 D - -
C
B 4 E - -
5 F - -
6 - - 7
D E F
…
N-2 - - N-1
N-1 - - -
9
9. Binary Trees and Binary Search Trees
Root = 0
Free = 2
Index item leftChild rightChild
0 A 1 -
A 1 B 3 4
2 - - 5
3 D - -
B
4 E - -
5 - - 6
D E 6 - - 7
…
N-2 - - N-1
N-1 - - -
• Alternatively, you may eliminate leftChild and rightChild fields, root and
free .
The root of a tree always start at 0. Children of item at index i (if they exist)
are 2*i+1 for left child and 2*i+2 for right child.
10
9. Binary Trees and Binary Search Trees
#include <stdexcept>
#include <string>
using namespace std;
11
9. Binary Trees and Binary Search Trees
// ********************************************************
// Header file BinaryTree.h for the ADT binary tree.
// ********************************************************
#include "TreeException.h"
#include "TreeNode.h" // contains definitions for TreeNode and TreeItemType
class BinaryTree
{
public:
// constructors and destructor:
BinaryTree();
BinaryTree(const TreeItemType& rootItem);
BinaryTree(const TreeItemType& rootItem, BinaryTree& leftTree,
BinaryTree& rightTree);
BinaryTree(const BinaryTree& tree);
virtual ~BinaryTree();
12
9. Binary Trees and Binary Search Trees
protected:
//The next four functions retrieve and set the values of the private data
// member root and child pointers. This is not used in here.
TreeNode *rootPtr() const;
void setRootPtr(TreeNode *newRoot);
void getChildPtrs(TreeNode *nodePtr, TreeNode * &leftChildPtr,
TreeNode * &rightChildPtr) const;
void setChildPtrs(TreeNode *nodePtr, TreeNode *leftChildPtr,
TreeNode *rightChildPtr);
private:
TreeNode *root; // pointer to root of tree
}; // End of header file.
13
9. Binary Trees and Binary Search Trees
• Discussion :
protected functions
if you do not want the instances (or objects) of a class to access the
internal data structure directly, use “protected” functions (these functions
are available for derived class)
function pointer
// ********************************************************
// Implementation file BinaryTree.cpp for the ADT binary
// tree.
// ********************************************************
#include "BinaryTree.h" // header file
#include <cstddef> // definition of NULL
#include <cassert> // for assert()
BinaryTree::BinaryTree() : root(NULL)
{
} // end default constructor
14
9. Binary Trees and Binary Search Trees
BinaryTree::BinaryTree(const TreeItemType& rootItem)
{
root = new TreeNode(rootItem, NULL, NULL);
assert(root != NULL);
} // end constructor
attachLeftSubtree(leftTree);
attachRightSubtree(rightTree);
} // end constructor
BinaryTree::~BinaryTree()
{
destroyTree(root);
} // end destructor
15
9. Binary Trees and Binary Search Trees
void BinaryTree::setRootData(const TreeItemType& newItem) throw(TreeException)
{
if (!isEmpty())
root->item = newItem;
else
{ root = new TreeNode(newItem, NULL, NULL);
if (root == NULL)
throw TreeException("TreeException: Cannot allocate memory");
} // end if
} // end setRootData
16
9. Binary Trees and Binary Search Trees
17
9. Binary Trees and Binary Search Trees
void BinaryTree::inorderTraverse(FunctionType visit)
{
inorder(root, visit);
} // end inorderTraverse
copyTree(treePtr->leftChildPtr, newTreePtr->leftChildPtr);
copyTree(treePtr->rightChildPtr, newTreePtr->rightChildPtr);
}
else
newTreePtr = NULL; // copy empty tree
} // end copyTree
18
9. Binary Trees and Binary Search Trees
19
9. Binary Trees and Binary Search Trees
• Sample Usage :
20
9. Binary Trees and Binary Search Trees
int main()
{
BinaryTree tree1, tree2, left; // empty trees
BinaryTree tree3(70); // tree with only a root 70
binTree.detachLeftSubtree(left);
left.inorderTraverse(display);
cout << "\n----------------------\n";
libra% a.out 60
10 20 30 40 50 60 70
20 70
----------------------
10 20 30 40 50
----------------------
10 40
10 20 30 40 50
----------------------
60 70
---------------------- 30 50
libra%
21
9. Binary Trees and Binary Search Trees
• Definition: a binary search tree is a binary tree that satisfies the following 3
properties
• Each node has record with unique key (or search key)
• All keys in left subtree < key in the root < All keys in right subtree
• Both left subtree and right subtree are binary search trees
20
60 30
15 25
70 5 40
65 90 2 12
22
9. Binary Trees and Binary Search Trees
+postorderTraverse(
in visit: FunctionType)
• A possible design for search key class & record class in binary search tree
23
9. Binary Trees and Binary Search Trees
// A class for a personal record with name, idNum, phoneNumber etc
// The searchKey is name (derived this class from class KeyedItem)
• Need to make sure that the tree is still a binary search tree after insertion!
• Starting from root, use search() strategy to locate the correct position
• If the item already in the tree, the item is not inserted.
• If the item is not in the tree, search() stops when the treePtr is NULL.
Which is the proper location for the new node. Let treePtr = new node.
24
9. Binary Trees and Binary Search Trees
5 15 5 15
25 25
4 7 4 7
25
9. Binary Trees and Binary Search Trees
• Example : May get different binary search trees if input orderings of data
are different
(1234) (4321)
(3412)
1
4
3
2
3
1 4
3 2
2
4 1
• Need to make sure that the tree is still a binary search tree after deletion!
• First, locate the desired node.
• Assume treePtr points to the desired node.
treePtr
It has only one child set treePtr to the valid child node
find the location of successor item, i.e. the node with smallest key
which is larger than deleted key.
The successor item is in the left most leaf (node X) of right subtree
copy successor item to the desired node’s item
delete node X (either case I or case II)
26
9. Binary Trees and Binary Search Trees
27
9. Binary Trees and Binary Search Trees
// Case III : have 2 subtrees
else
{
// find the successor item; replace the desired item with it
processLeftmost(nodePtr -> rightChildPtr, successorItem)
nodePtr->item = successorItem
}
}
// delete the smallest item in the tree with root NodePtr, return the item
processLeftmost(inout nodePtr:TreeNodePtr, out treeItem:TreeItemType)
{
if (nodePtr->leftChildPtr == NULL) // this is the successor item
{
treeItem = nodePtr->Item
delPtr = nodePtr
28
9. Binary Trees and Binary Search Trees
• Inorder listing of a binary search tree
• Theorem : The inorder traversal of binary search tree will visit its nodes
in sorted search key order
• Example :
40
Result :
30 50 30 35 37 45 47 50 55 60
37 45 60
35 47 55
• Assume a binary search tree with N nodes, the maximum height is N, and
minimum height is log2(N+1)
• Worst case running time of binary search tree operation, let h = height of
binary tree
Note : In CSC510, you will study how to maintain a balanced binary search
tree, i.e. minimum height binary search tree (only need to consider insertion
and deletion operations) the height of the tree is O(log N)
Worst case running time of above operations (excluding Traversal) are
O(log N)
29
9. Binary Trees and Binary Search Trees
treeItemType Item;
ptrType leftChild; // point to left child
ptrType rightSibling; // point to right child
• Example :
B C D
E F G H I
B C D
E F G
H I
30