Data Structures – CSC212 (1) Dr Muhammad Hussain Lecture - Binary Tree ADT Binary Tree ADT It is...
-
Upload
cornelius-french -
Category
Documents
-
view
218 -
download
0
Transcript of Data Structures – CSC212 (1) Dr Muhammad Hussain Lecture - Binary Tree ADT Binary Tree ADT It is...
Data Structures – CSC212 (1)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Binary Tree ADTIt is an ordered tree with the following properties
1. Each node can have at most two subtrees
2. Each subtree is identified as being either left subtree or the right subtree of its parent
3. It may be empty
Note: Property 1 says that each node can have maximum two
children The order between the children of a node is specified by
labeling its children as left child and right child
Data Structures – CSC212 (2)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Why binary Trees? Why binary Trees?
1.1. Expression TreeExpression Tree - A central data structure in compiler design- A central data structure in compiler design
- Interior nodes contain operators and the leaf nodes have operands- Interior nodes contain operators and the leaf nodes have operands- An expression is evaluated by applying the operator at root to the - An expression is evaluated by applying the operator at root to the values obtained by recursively evaluating the left and right subtreesvalues obtained by recursively evaluating the left and right subtrees- The following tree corresponds the expression: (a+((b-c)*d)- The following tree corresponds the expression: (a+((b-c)*d)
+
a *
- d
b c
Binary trees naturally arise in many different applications
Data Structures – CSC212 (3)
Dr Muhammad Hussain Lecture - Binary Tree ADT
2.2. Huffman Coding TreeHuffman Coding Tree - Its is used in a simple but effective data compression algorithm - Its is used in a simple but effective data compression algorithm
- In this tree, each symbol is stored at a leaf node- In this tree, each symbol is stored at a leaf node- To generate the code of a symbol traverse the tree from the root to - To generate the code of a symbol traverse the tree from the root to the leaf node that contains the symbol such that each left link the leaf node that contains the symbol such that each left link corresponds to 0 and each right link corresponds to 1 corresponds to 0 and each right link corresponds to 1 - The following tree encodes the symbols a, b, c, d - The following tree encodes the symbols a, b, c, d
a
d
b c
10
10
10
The code of a is 0, and that of b is 100The code of a is 0, and that of b is 100
Why binary Trees? Why binary Trees?
Data Structures – CSC212 (4)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Recursive definition of Binary TreeRecursive definition of Binary Tree
A binary tree is A binary tree is - empty OR- empty OR- a node, called the root node, together with two binary - a node, called the root node, together with two binary trees, which are disjoint from each other and the root trees, which are disjoint from each other and the root node. These are called left and right subtrees of the root node. These are called left and right subtrees of the root
Many routines can be efficiently implemented using recursive nature of the binary Many routines can be efficiently implemented using recursive nature of the binary treetree
Data Structures – CSC212 (5)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Types of Binary TreeTypes of Binary Tree
FullFull - Every node has exactly two children in all levels, - Every node has exactly two children in all levels, except the last level. Nodes in last level have 0 except the last level. Nodes in last level have 0 childrenchildren
CompleteComplete - Full up to second last level and last level is - Full up to second last level and last level is filled from left to right filled from left to right
Other Other - not full or complete- not full or complete
Data Structures – CSC212 (6)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or Other?or Other?
AA
CC DD
FFII EE
BB
RRSS PP
GGHH
TT
MMLL OOKKJJ
NN
not binarynot binary
Data Structures – CSC212 (7)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or or other?other?
AA
DD
FFII
BB
RRSS PP
GGHH
TT
MMLL OOKK NN
Data Structures – CSC212 (8)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or or other?other?
AA
DD
FFII
BB
RRSS PP
GGHH
TT
MMLL OOKK NN
Data Structures – CSC212 (9)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or or other?other?
AA
DD
FFII
BB
RRSS PP
GGHH
TT
MMLL OOKK NN
Data Structures – CSC212 (10)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or or other?other?
AA
DD
FFII
BB
RR
SS
PP
GGHH
TT
MMLL OOKK NN
Data Structures – CSC212 (11)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or Other?or Other?
AA
DD
FFII
BB
SS
RR
GGHH
TT
MMLL PPKK NN OO
Data Structures – CSC212 (12)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or other?or other?
AA
DD
FFII
BB
SS
RR
GGHH
TT
MMLL PPKK NN OO
Data Structures – CSC212 (13)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Full, Full, Complete Complete or Other?or Other?
AA
DD
FFII
BB
QQ RR
GGHH
MMLL PPKK NN OO
Data Structures – CSC212 (14)
Dr Muhammad Hussain Lecture - Binary Tree ADT
ProcessTo process a node means to perform some simple operation like printing the contents of the node or updating the contents of the node
TraversalTo traverse a finite collection of objects means to process each object in the collection exactly once
Examples1. List traversal – to process each element of list exactly once2. Tree traversal – to process each node of tree exactly once
Binary Tree TraversalBinary Tree Traversal
Data Structures – CSC212 (15)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Traversal Of Binary TreeThere are four methods for the traversal of a binary tree 1. Preorder Traversal
Each node is processed before any node in either of its subtrees2. Inorder Traversal
Each node is processed after all nodes in its left subtree and before any node in its right subtree
3. Postorder TraversalEach node is processed after all nodes in both of its subtrees
4. Level order TraversalEach node at level l is processed before any node at level l+1
Data Structures – CSC212 (16)
Dr Muhammad Hussain Lecture - Binary Tree ADT
A
D
FI
B
RS P
GH
T
ML OK N
Preorder Traversals1. Visit the root
2. Visit Left subtree
3. Visit Right subtree
1
2
3
4 5
6 7
8
9 10
11
12 13
14
15 16
Data Structures – CSC212 (17)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Algorithm TraversePreorder(n)
Process node n
if n is an internal node then
TraversePreorder( n -> leftChild)
TraversePreorder( n -> rightChild)
Data Structures – CSC212 (18)
Dr Muhammad Hussain Lecture - Binary Tree ADT
A
D
FI
B
RS P
GH
T
ML OK N
1
Inorder Traversals1. Visit Left subtree
2. Visit the root
3. Visit Right subtree
1
3
4
5
7
8
9
10
11
12
13
14
15
16
1
1
6
2
Data Structures – CSC212 (19)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Algorithm TraverseInorder(n)
if n is an internal node then
TraverseInorder( n -> leftChild)
Process node n
if n is an internal node then
TraverseInorder( n -> rightChild)
Data Structures – CSC212 (20)
Dr Muhammad Hussain Lecture - Binary Tree ADT
A
D
FI
B
RS P
GH
T
ML OK N
Postorder Traversals1. Visit Left subtree
2. Visit Right subtree
3. Visit the root
1
2 3
4
5
6 7
8
9
10
11 12
13
14
15
16
2
23
Data Structures – CSC212 (21)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Algorithm TraversePostorder(n)
if n is an internal node then
TraversePostorder( n -> leftChild)
TraversePostorder( n -> rightChild)
Process node n
Data Structures – CSC212 (22)
Dr Muhammad Hussain Lecture - Binary Tree ADT
B
H
M N
A
D
FI
B
RS P
GH
T
ML OK N
Level Order Traversals1. Visit the root
2. Visit root of Left subtree
3. Visit root of Right subtree
4. ???
1
3
4 5 6 7 8
9 10 11 12 13 14
15 16
2
17 18 19 20
Data Structures – CSC212 (23)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Specification of Binary Tree ADTSpecification of Binary Tree ADTElements: Elements: Any data typeAny data type
Structure: Structure: A binary tree either is empty OR a node, called the root node, A binary tree either is empty OR a node, called the root node, together with two binary trees, which are disjoint from each together with two binary trees, which are disjoint from each other and the root other and the root node. These are called left and right node. These are called left and right subtrees of the rootsubtrees of the root
Domain: Domain: Number of elements is boundedNumber of elements is bounded
Operations:Operations:
OperationOperation SpecificationSpecification
void void emptyempty(()) Precondition/Requires:Precondition/Requires: none.none.Processing/Results:Processing/Results: returns true if the binary tree (BT) has no nodes.returns true if the binary tree (BT) has no nodes.
void void traversetraverse(Order (Order ord)ord)
Precondition/Requires:Precondition/Requires: BT is not empty.BT is not empty.Processing/Results: Processing/Results: Traverses the binary tree according to the value of ordTraverses the binary tree according to the value of ord(1) (1) ord = preOrderord = preOrder: traverses the tree using preorder traversal: traverses the tree using preorder traversal(2) (2) ord = inOrderord = inOrder: traverses the tree using inorder traversal: traverses the tree using inorder traversal(3) (3) ord = postOrderord = postOrder: traverses the tree using postorder traversal: traverses the tree using postorder traversal
Data Structures – CSC212 (24)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Operation Specification
void find (Relative rel)
Precondition/Requires: BT is not empty.Processing/Results: the current node of BT is determined by Relative and the
current node prior to the operation as follows (always return true unless indicated so):
(1) rel = Root: current = root(2) rel = Parent: if the current node has a parent then parent is the current node;
otherwise returns false(3) rel = LeftChild: if the current node has a leftchild then it will be the current
node; otherwise returns false(4) rel = RightChild: same as above but for rightchild.
void insert(Relative rel, Type val)
Precondition/Requires: either (1) BT is empty and rel = Root; or (2) BT not empty and rel Root .
Processing/Results: as follows:(1) rel = Root: create a root node with data = val.(2) rel = Parent: nonsense case.(3) rel = LeftChild: if current node does not have a leftchild then make one with
data = val.(4) rel = RightChild: same as above but for rightchild. In all the above cases if the insertion was successful then it will be designated
as current node and returns true, otherwise current remains unchanged and returns false.
Data Structures – CSC212 (25)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Operation Specification
void update(Type) Precondition/Requires: BT is not empty.Processing/Results: update the value of data of the current node.
Type retrieve() Precondition/Requires: BT is not empty.Processing/Results: returns data of the current node.
void delete_sub() Precondition: BT is not empty.Process: the subtree whose root node was the current node before this operation is deleted from the tree. In case the resulting tree is not empty then current = root.
Note: Relative is enumerated type and is confined to the values {Root, Parent, LeftChild, RightChild}
Data Structures – CSC212 (26)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Represent ion of Binary Tree ADTRepresent ion of Binary Tree ADT
A binary tree can represented using A binary tree can represented using - - Linked ListLinked List- - ArrayArray
NoteNote : Array is suitable only for full and complete : Array is suitable only for full and complete binary treesbinary trees
Data Structures – CSC212 (27)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Linked List based ImplementationLinked List based Implementationpublic class public class BTNodeBTNode <T> <T>{{ public T public T datadata;; public BTNode<T> public BTNode<T> left, rightleft, right;;
public BTNode(T val)public BTNode(T val) {{ data = val;data = val; left = right = null;left = right = null; }} public BTNode(T val, BTNode<T> l, BTNode<T> r)public BTNode(T val, BTNode<T> l, BTNode<T> r) {{ data = val;data = val; left = l;left = l; right = r;right = r; }}}}
public enum OrderOrder {preOrder, inOrder, postOrder};
Data Structures – CSC212 (28)
Dr Muhammad Hussain Lecture - Binary Tree ADT
public class public class BTBT<T>{<T>{//Data Members//Data Members
BTNode<T> root, current;BTNode<T> root, current; public BT()public BT()
// Private Methods// Private Methods private void preorder(BTNode<T> p)private void preorder(BTNode<T> p)
private void inorder(BTNode<T> p)private void inorder(BTNode<T> p) private void postorder(BTNode<T> p)private void postorder(BTNode<T> p)
private BTNode<T> findparent (BTNode<T> p)private BTNode<T> findparent (BTNode<T> p) // non-recursive // non-recursive private BTNode<T> findparent (BTNode<T> p, BTNode<T> private BTNode<T> findparent (BTNode<T> p, BTNode<T>
t)t)// Operations// Operationspublic void traverse(Order ord)public void traverse(Order ord)public boolean empty()public boolean empty()
public boolean find (Relative rel)public boolean find (Relative rel)public boolean insert (Relative rel, T val) public boolean insert (Relative rel, T val) public T retrieve ()public T retrieve ()public void update (T val)public void update (T val)
public void delete_subtree()public void delete_subtree()}}public enum Relative {Root, Parent, LeftChild, RightChild};
Data Structures – CSC212 (29)
Dr Muhammad Hussain Lecture - Binary Tree ADT
private void preorderpreorder(BTNode<T> p){ if (p != null){ System.out.println(p.data); preorder(p.left); preorder(p.right); }}
private void inorderinorder(BTNode<T> p){ if (p != null){ inorder(p.left); System.out.println(p.data); inorder(p.right); }}
Implementation of Private MethodsImplementation of Private Methods
Data Structures – CSC212 (30)
Dr Muhammad Hussain Lecture - Binary Tree ADT
private void postorder(BTNode<T> p){ if (p != null){ postorder(p.left); postorder(p.right); System.out.println(p.data); }}
Implementation of Private MethodsImplementation of Private Methods
Data Structures – CSC212 (31)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Implementation of Private MethodsImplementation of Private Methods
/* Non-recursive version of findparent */private BTNode<T> findparentfindparent (BTNode<T> p){ LinkStack<BTNode<T>> stack = new LinkStack<BTNode<T>>(); BTNode<T> q = root; while (q.right != p && q.left != p){ if (q.right != null) stack.push(q.right); if (q.left != null) q = q.left; else q = stack.pop(); } return q;}
Data Structures – CSC212 (32)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Implementation of Private MethodsImplementation of Private Methods
/* Recursive version of findparent - uses pre-order traversal */private BTNode<T> findparentfindparent (BTNode<T> p, BTNode<T> t){ if (t == null) return null; /* empty tree */ if (t.right == null && t.left == null) return null; else if (t.right == p || t.left == p) return t; /* parent is t */ else { BTNode q = findparent(p, t.left); if (q != null) return q; else return findparent(p, t.right); }}
Data Structures – CSC212 (33)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Implementation of OperationsImplementation of Operations
public void traverse(Order ord){ switch (ord) { case preOrder: preorder(root); break; case inOrder: inorder(root); break; case postOrder: postorder(root); break; default: break; } return;}
public BT(){ root = current = null;}
Data Structures – CSC212 (34)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Implementation of OperationsImplementation of Operationspublic boolean findfind (Relative rel){ switch (rel) { case Root: current = root; return true; case Parent: if (current == root) return false; current = findparent(current, root); return true; case LeftChild: if (current.left == null) return false; current = current.left; return true; case RightChild: if (current.right == null) return false; current = current.right; return true; default: return false; }}
Data Structures – CSC212 (35)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Implementation of OperationsImplementation of Operationspublic boolean insertinsert (Relative rel, T val) { switch (rel) { case Root: if (! empty()) return false; current = root = new BTNode<T>(val); return true; case Parent: return false; case LeftChild: if (current.left != null) return false; current.left = new BTNode<T>(val); current = current.left; return true; case RightChild: if (current.right != null) return false; current.right = new BTNode<T> (val); current = current.right; return true; default: return false; } }
Data Structures – CSC212 (36)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Implementation of OperationsImplementation of Operationspublic T retrieve (){ return current.data;}
public void update (T val){ current.data = val;}
Data Structures – CSC212 (37)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Implementation of OperationsImplementation of Operations
public void delete_subtree(){ if (current == root){ current = root = null; } else { BTNode<T> p = current; find(Relative.Parent); if (current.left == p) current.left = null; else current.right = null; current = root; }}
Data Structures – CSC212 (38)
Dr Muhammad Hussain Lecture - Binary Tree ADT
Height and the number of nodes in a Binary Tree If the height of a binary tree is h then the maximum number of nodes in the tree is 2h -1 If the number of nodes in a complete binary tree is n, then
2h - 1 = n 2h = n + 1
h = log(n+1) O(logn)O(logn)