Post on 02-Jan-2016
8 - 1
8Tree ADTs
• Tree concepts.
• Applications of Trees.
• A Tree ADT – requirements, contract.
• Linked implementation of Trees.
• Binary Tree ADTs.
• Binary Search Tree (BST)
8 - 2
Non Linear Linked Structures
• General term is a graph.
• Applications: many real world networking problems including communications, roads, airline routes.
6
3
1
4
7
5
2
8 - 3
Trees
• A tree consists of a set of nodes and a set of directed edges
• A tree can be defined that connect pairs of nodes. • We consider only rooted trees. A rooted tree has the
following properties. – One node is distinguished as the root. – Every node c, except the root, is connected by an edge
from exactly one other node p. – Node p is c's parent, and c is one of p's children. – A unique path traverses from the root to each node. – The number of connects that must be followed is the path
length.
8 - 4
Tree Height and Depth
A tree, with height and depth information
Height 3
0
Depth 0
3
8 - 5
Trees
• Nodes with the same parent are called siblings• An alternative definition of the tree is recursive:• Either a tree is empty or it consists of a root and zero
or more nonempty subtrees T,, T2, . . . , Tk, each of whose roots are connected by an edge from the root
A tree viewed recursively
8 - 6
Tree concepts
• A tree is a hierarchical collection of elements, and is a generalization of the binary trees.
• A tree consists of nodes. • Each node has an element, and has branches
leading to a number of other nodes (its children).• The tree has a unique root node.• Every node, apart from the root node, is the child of
exactly one other node (its parent).
8 - 7
Applications of trees
Trees occur frequently in real life:
• An organization tree records the structure of a hierarchical organization, such as the divisional structure within a business or university.
University
Engineering Medicine Science Education SocialScience
Humanities
Chemistry Physics Biology Mathe-matics
ComputerScience
Languages History
8 - 8
Applications of trees (continued)
• A taxonomy is a classification of organisms or plants.
animals
worms insects arachnids vertebrates stars sponges
ants beetles flies fish amphibians reptiles birds mammals
snakes lizards crocodiles
8 - 9
Applications of trees (continued)
• A family tree records human parent–child relationships.– Our strict definition limits us to one parent per child, but
we could model a complete family history by a pair of trees, one for mother–child relationships, and another for father–child relationships.
Archy
George Frank Colin Joe
Fred David Maggie Ann
Jeff Emma JonSusie
8 - 10
Example: file hierarchies
• A file hierarchy is a collection of documents (or plain files) and folders (or directories).
• A folder can contain documents and other folders, to any depth.
• We can model a file hierarchy by a tree in which documents are modeled by leaf nodes and (nonempty) folders are modeled by parent nodes.
8 - 11
Example: file hierarchies (continued)
• For example:
doc bin lib etc
cp grep sort mail motd passwd
aliases
tmp users
8 - 12
Tree ADT: requirements
• Requirements:
1 It must be possible to access the root of a tree.
2 It must be possible to access all ancestors of any node in a tree.
3 It must be possible to access all descendants of any node in a tree.
4 It must be possible to add a new node to a tree, either as the root node or as the child of an existing node.
5 It must be possible to remove a given node from a tree, together will all its descendants.
6 It must be possible to traverse a tree.
8 - 13
Tree ADT: contract
• Possible contract:
class Tree {// Each Tree object is a tree whose
elements // are arbitrary objects.
8 - 14
Tree ADT: contract (continued)
//////////// Accessors ////////////
public: TreeNode root ();// Return the root node of this tree.
TreeNode parent (TreeNode node);
// Return the parent of node in this tree, or null// if node is the root node.
int childCount (TreeNode node);// Return the number of children of node in// this tree.
Object getElement ();// Return the element contained in this node.
8 - 15
Tree ADT: contract (continued)
//////////// Transformers ////////////
void makeRoot (Object elem);// Make this tree consist of just a root node// containing element elem.
TreeNode addChild (TreeNode node, Object elem);
// Add a new node containing elem as a child of// node in this tree, and return the new node. The// new node has no children of its own.
void remove (TreeNode node);// Remove node from this tree, together with all its// descendants.
8 - 16
Tree ADT: contract (continued)
//////////// Transformers - continued //////////
void setElement (Object elem);// Change the element contained in this node to// be elem
8 - 17
Linked implementation of trees
• There are many possible implementations of the tree ADT.
• Here will we consider a linked implementation based on SLLs.
• We can distinguish between two different kinds of tree:In an unordered tree, each parent has a set of children.In an ordered tree, each parent has a list of children.
• A Set can be built as an unsorted SLL.
• This will be adequate here, since the number of children per parent tends to be quite small.
8 - 18
Implementation of unordered trees
• Example:
Archy
FrankGeorge
Fred
Colin Joe
David
Susie Jeff
Maggie Ann
Emma Jon
link to first child
link to next sibling
link to parent
8 - 19
Implementation of unordered trees (cont’d)• Summary of algorithms (where c is the maximum number of
children per parent):
Operation Algorithm Time complexity
parent Follow link (trivial) O(1)
addChild SLL insertion before first node O(1)
remove SLL deletion O(c)
• O(c) could mean O(n) if tree consists of a root node withn – 1 children.
• Typically, though, c does not grow in proportion to n.
8 - 20
Implementation of ordered trees
• To implement an ordered tree, we must preserve the order in which the children are added. So add each new child at the end of the SLL.
• Summary of algorithms (where c is the maximum number of children per parent):
Operation Algorithm Time complexity
parent Follow link (trivial) O(1)
addChild SLL insertion after last node O(c)
remove SLL deletion O(c)
• O(c) could mean O(n) if tree consists of a root node withn – 1 children.
8 - 21
Specialized tree ADTs
• Our tree ADT is very general:– it allows nodes to contain arbitrary elements;– it allows each node to have an arbitrary number of
children.
• Often, a particular application will require a more specialized structure.
• In this case, we can design and implement a specialized tree ADT.
8 - 22
Building a General Tree
• In a general tree each node may have any number of children.
• Also any node except root my have siblings.
8 - 23
Left Child - Right Sibling
A
B C D
E F G H I J
K L M
data
left child right sibling
Tree Node structure
A Tree Node structure could include also a pointer to Node’s parent
8 - 24
Tree ADT• Objects: any type of objects can be stored in a tree
• Methods:
• accessor methods– root() – return the root of the tree– parent(p) – return the parent of a node– children(p) – returns the children of a node
• query methods– size() – returns the number of nodes in the tree – isEmpty() - returns true if the tree is empty– elements() – returns all elements– isRoot(p), isInternal(p), isExternal(p)
8 - 25
Tree Implementation
A C++ implementation for a Tree Node is:
struct tnode {
int key; // Node Information
struct tnode* lchild; // Node Communication
struct tnode* sibling; // Node Communication
} ;
- Create a tree with three nodes (one root & two children)
- Insert a new node (in tree with root R, as a new child at level L)
- Delete a node (in tree with root R, the first child at level L)
8 - 26
Tree Traversal
• Two main methods:– Preorder– Postorder
• Recursive definition• PREorder:
– visit the root– traverse in preorder the children (subtrees)
• POSTorder– traverse in postorder the children (subtrees)– visit the root
8 - 27
Preorder• preorder traversal
Algorithm preOrder(v)“visit” node vfor each child w of v do
recursively perform preOrder(w)
8 - 28
Postorder• postorder traversal
Algorithm postOrder(v)
for each child w of v do
recursively perform postOrder(w)
“visit” node v
• du (disk usage) command in Unix
8 - 29
Preorder Implementation
public void preorder(ptnode t) {
ptnode ptr;
display(t->key);
for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) {
preorder(ptr);
}
}
8 - 30
Postorder Implementation
public void postorder(ptnode t) {
ptnode ptr;
for(ptr = t->lchild; NULL != ptr; ptr = ptr->sibling) {
postorder(ptr);
}
display(t->key);
}
8 - 31
Binary Trees
• A special class of trees: max degree for each node is 2 (children)
• Recursive definition: A binary tree is a finite set of nodes that is either empty or consists of a root and two disjoint binary trees called the left subtree and the right subtree.
• Any tree can be transformed into binary tree.– by left child-right sibling representation
8 - 32
Example
J
IM
HL
A
B
C
D
E
F G K
8 - 33
Binary Tree ADT
objects: a finite set of nodes either empty or consisting of a root node, left BinaryTree, and right BinaryTree.
8 - 34
Samples of Binary Trees
A
B
A
BA
B C
GE
I
D
H
F
Complete Binary Tree
Skewed Binary Tree
E
C
D
1
2
3
45
8 - 35
Full BT vs. Complete BT
A
B C
GE
K
D
J
F
IH ONML
Full binary tree of depth 4
A
B C
GE
I
D
H
F
Complete binary tree
8 - 36
SLL Representation of BT
struct TreeNode{
char data; // Node Information
TreeNode *left, *right; // Node Communication
};
dataleft
right
data
left right
8 - 37
Binary Tree ADT
• The C++ Tree SLL ADT implementation:class TreeSLL{private:
int NoNodes;public: //////////// Constructor //////////// TreeNode *Root; TreeSLL (char c) {
NoNodes = 0;Root = NEW (c); // Initiates the Root
};
8 - 38
Binary Tree ADT
• The C++ Tree SLL ADT implementation:
//////////// Accessors ////////////
int Size () {
return NoNodes; };
8 - 39
Binary Tree ADT
• The C++ Tree SLL ADT implementation:
//////////// Accessors ////////////// Traverse Tree and print Tree nodes PostOrder
void PostOrder(TreeNode* ptr) {
if(ptr){
PostOrder(ptr->left);
PostOrder(ptr->right);
cout << ptr->data << " ";
}
}
8 - 40
Binary Tree ADT
• The C++ Tree SLL ADT implementation:
//////////// Accessors ////////////// Traverse Tree and print Tree nodes PostOrder
void PostOrder(TreeNode* ptr) {
if(ptr){
PostOrder(ptr->left);
PostOrder(ptr->right);
cout << ptr->data << " ";
}
}
8 - 41
Binary Tree ADT
• The C++ Tree SLL ADT implementation:
//////////// Accessors ////////////// Traverse Tree and print Tree nodes PreOrder
void PreOrder(TreeNode* ptr) {
if(ptr){
cout << ptr->data << " ";
PreOrder(ptr->left);
PreOrder(ptr->right);
}
}
8 - 42
Binary Tree ADT
• The C++ Tree SLL ADT implementation:
//////////// Accessors ////////////// Traverse Tree and print Tree nodes InOrder
void InOrder(TreeNode* ptr) {
if(ptr){
InOrder(ptr->left);
cout << ptr->data << " ";
InOrder(ptr->right);
}
}
8 - 43
Binary Tree ADT
• The C++ Tree SLL ADT implementation:
//////////// Transformers ////////////// Create the Binary Tree Node:
TreeNode* NEW(char c)
{ TreeNode* p = new TreeNode;
p->data=c;
p->left=p->right=NULL;
NoNodes++;
return p;
}
8 - 44
Binary Tree ADT
• The C++ Tree SLL ADT implementation:
//////////// Transformers ////////////// Add node as a left child of p
void AddLeft(TreeNode* p,char c) {
TreeNode* q=NEW(c);
p->left=q; }
// Add node as a left child of p
void AddRight(TreeNode* p,char c) {
TreeNode* q=NEW(c);
p->right=q; }
8 - 45
Binary Tree ADTvoid main()
{
TreeSLL BTree('-'); // 5*x / 2 - 6
BTree.AddLeft(BTree.Root,'/');
BTree.AddRight(BTree.Root->left,'2');
BTree.AddLeft(BTree.Root->left,'+');
BTree.AddLeft(BTree.Root->left->left,'x');
BTree.AddRight(BTree.Root->left->left,'3');
BTree.AddRight(BTree.Root,'6');
cout << "No of Tree Nodes = " << BTree.Size () << endl;
cout << "Postorder\t"; // Postorder x 3 + 2 / 6 -
BTree.PostOrder(BTree.Root); cout << endl;
cout << "Preorder \t"; // Preorder - / + x 3 2 6
BTree.PreOrder(BTree.Root); cout << endl;
cout << "Inorder \t"; // Inorder x + 3 / 2 - 6
BTree.InOrder(BTree.Root); cout << endl;
}
BT_Trav2.CPP
8 - 46
Binary Tree ADT
• Output
No of Tree Nodes = 7
Postorder x 3 + 2 / 6 -
Preorder - / + x 3 2 6
Inorder x + 3 / 2 - 6
BT_Trav2.CPP