Upload
mubashar-mehmood
View
71
Download
0
Embed Size (px)
DESCRIPTION
basic information about Tree, how to implement them into algorithms.
Citation preview
Presented by:Mubashar Mehmood
Implementation of Trees
A tree is a nonlinear data structure that models a hierarchical organization.
A tree consists of nodes with a parent-child relation.
Every node except one has a unique parent. There is a unique path from root node to
each child node.
Tree
A
B
D E
C
List Tree
Start head root# before 1 (prev) 1 (parent)# after 1 (next) >= 1 (children)
Comparison of Tree and List
Binary tree associated with an arithmetic expression internal nodes: operators external nodes: operands
Example: arithmetic expression tree for the expression (2 (a - 1) + (3 b))
Arithmetic Expression Tree
+
-2
a 1
3 b
Binary tree associated with a decision process internal nodes: questions with yes/no answer external nodes: decisions
Example: dining decision
Decision Tree
Want a fast meal
How about coffee On expense account
Starbucks Wendy’s Gotham Apple
Yes No
Yes No Yes No
A special class of trees: max degree for each node is 2.
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.
Binary Trees
B
E
H I
Sequential Representation
Binary Tree Representations
A
B
E
C
D
AB--C------D--.E
[1][2][3][4][5][6][7][8][9].[16]
(1) waste space(2) insertion/deletion problem
ABCDEFGHI
[1][2][3][4][5][6][7][8][9]
A
B C
GE
I
D
H
F
Linked Representation
Binary Tree Representations
dataleft right
left right
data
• Let L, V, and R stand for moving left, visiting the node, and moving right.
• There are six possible combinations of traversal• lRr, lrR, Rlr, Rrl, rRl, rlR
• Adopt convention that we traverse left before right, only 3 traversals remain• lRr, lrR, Rlr• inorder, postorder, preorder
Binary Tree Traversals
Binary Tree Traversals
+
*
A
*
/
E
D
C
B
inorder traversalA / B * C * D + Einfix expressionpreorder traversal+ * * / A B C D Eprefix expressionpostorder traversalA B / C * D * E +postfix expression
Inorder Traversal
3
1
2
5
7 9
8
4
6
Algorithm inOrder(v)if hasLeft (v)
inOrder (left (v))visit(v)if hasRight (v)
inOrder (right (v))