unit 1 (9hrs) trees...unit 1 (9hrs) trees mahesh sanghavi & deepali pawar department of computer...
TRANSCRIPT
Unit 1 (9Hrs)
TreesMahesh Sanghavi & Deepali Pawar
Department of Computer Engineering,
SNJB’s KBJ College of Engineering, Chandwad, India
The class notes are a compilation and edition from many sources. The instructor does not claim intellectual property or
ownership of the lecture notes.
Syllabus
• Tree-• basic terminology, • General tree and its representation, • representation using sequential and linked organization, • Binary tree- properties, • converting tree to binary tree, • binary tree traversals- inorder, preorder, post order, • level wise -depth first and breadth first, • Operations on binary tree. • Binary Search Tree (BST), BST operations, • Threaded binary tree- concepts, threading, insertion and deletion of nodes in in-
order threaded binary tree, in order traversal of in-order threaded binary tree. • Case Study- Use of binary tree in expression tree-evaluation and Huffman's coding
Nature View of a Tree
branches
leaves
root
Computer Scientist’s View
branches
leaves
root
nodes
What is a Tree• A tree is a finite nonempty set
of elements.
• It is an abstract model of a hierarchical structure.
• consists of nodes with a parent-child relation.
• Applications:• Organization charts
• File systems
• Programming environments
Computers”R”Us
Sales R&DManufacturing
Laptops DesktopsUS International
Europe Asia Canada
subtree
Tree Terminology• Root: node without parent (A)
• Siblings: nodes share the same parent
• Internal node: node with at least one child (A, B, C, F)
• External node (leaf ): node without children (E, I, J, K, G, H, D)
• Ancestors of a node: parent, grandparent, grand-grandparent, etc.
• Descendant of a node: child, grandchild, grand-grandchild, etc.
• Depth of a node: number of ancestors
• Height of a tree: maximum depth of any node (3)
• Degree of a node: the number of its children
• Degree of a tree: the maximum number of its node.
A
B DC
G HE F
I J K
Subtree: tree consisting of a node and its descendants
Introduction (3/8)
• Some Terminology• node: the item of information plus the branches to each node.
• degree: the number of subtrees of a node
• degree of a tree: the maximum of the degree of the nodes in the tree.
• terminal nodes (or leaf): nodes that have degree zero
• nonterminal nodes: nodes that don’t belong to terminal nodes.
• children: the roots of the subtrees of a node X are the childrenof X
• parent: X is the parent of its children.
Introduction (4/8)
• Some Terminology (cont’d)• siblings: children of the same parent are said to be siblings.
• Ancestors of a node: all the nodes along the path from the root to that node.
• The level of a node: defined by letting the root be at level one. If a node is at level l, then it children are at level l+1.
• Height (or depth): the maximum level of any node in the tree
Introduction (5/8)
• ExampleA is the root nodeB is the parent of D and EC is the sibling of BD and E are the children of BD, E, F, G, I are external nodes, or leavesA, B, C, H are internal nodesThe level of E is 3The height (depth) of the tree is 4The degree of node B is 2The degree of the node C is 3The ancestors of node I is A, C, HThe descendants of node C is F, G, H, I
A
B C
H
ID E F G
Level
1
2
3
4
Property: (# edges) = (#nodes) - 1
Tree ADT
• We use positions to abstract nodes
• Generic methods:
• integer size()
• boolean isEmpty()
• objectIterator elements()
• positionIterator positions()
• Accessor methods:
• position root()
• position parent(p)
• positionIterator children(p)
Query methods:
boolean isInternal(p)
boolean isExternal(p)
boolean isRoot(p)
Update methods:
swapElements(p, q)
object replaceElement(p, o)
Additional update methods may be defined by data structures implementing the Tree ADT
Intuitive Representation of Tree Node
List Representation
( A ( B ( E ( K, L ), F ), C ( G ), D ( H ( M ), I, J ) ) )
The root comes first, followed by a list of links to sub-trees
Data Link 1 Link 2 … Link n
How many link fields are needed in
such a representation?
Trees
• Every tree node:• object – useful information
• children – pointers to its children
Data
Data Data Data
Data Data Data
A Tree Representation
• A node is represented by an object storing• Element
• Parent node
• Sequence of children nodes
B
DA
C E
F
B
A D F
C
E
Left Child, Right Sibling Representation
Data
Left
Child
Right
Sibling A
B C D
IHGFE
J K L
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
Preorder Traversal
• A traversal visits the nodes of a tree in a systematic manner
• In a preorder traversal, a node is visited before its descendants
• Application: print a structured document
Become Rich
1. Motivations 3. Success Stories2. Methods
2.1 Get a CS PhD
2.2 Start a
Web Site
1.1 Enjoy Life
1.2 Help Poor Friends
2.3 Acquired
by Google
1
2
3
5
4 6 7 8
9
Algorithm preOrder(v)
visit(v)
for each child w of v
preorder (w)
Postorder Traversal
• In a postorder traversal, a node is visited after its descendants
• Application: compute space used by files in a directory and its subdirectories
Algorithm postOrder(v)
for each child w of v
postOrder (w)
visit(v)
cs16/
homeworks/todo.txt
1Kprograms/
DDR.java10K
Stocks.java25K
h1c.doc3K
h1nc.doc2K
Robot.java20K
9
3
1
7
2 4 5 6
8
Binary Tree
• A binary tree is a tree with the following properties:
• Each internal node has at most two children (degree of two)
• The children of a node are an ordered pair
• We call the children of an internal node left child and right child
• Alternative recursive definition: a binary tree is either
• a tree consisting of a single node, OR
• a tree whose root has an ordered pair of children, each of which is a binary tree
Applications:arithmetic expressions
decision processes
searching
A
B C
F GD E
H I
BinaryTree ADT• The BinaryTree ADT extends
the Tree ADT, i.e., it inherits all the methods of the Tree ADT
• Additional methods:• position leftChild(p)
• position rightChild(p)
• position sibling(p)
• Update methods may be defined by data structures implementing the BinaryTree ADT
Examples of the Binary Tree
A
B C
GE
I
D
H
F
Complete Binary Tree
1
2
3
4
A
B
A
B
Skewed Binary Tree
E
C
D
5
Differences Between A Tree and A Binary Tree
• The subtrees of a binary tree are ordered; those of a tree are not ordered.
• Are different when viewed as binary trees.
• Are the same when viewed as trees.
A
B
A
B
Data Structure for Binary Trees
• A node is represented by an object storing
• Element
• Parent node
• Left child node
• Right child node
B
DA
C E
B
A D
C E
Arithmetic Expression Tree
• 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))
+
-2
a 1
3 b
Decision Tree
• Binary tree associated with a decision process• internal nodes: questions with yes/no answer
• external nodes: decisions
• Example: dining decision
Want a fast meal?
How about coffee? On expense account?
Starbucks Spike’s Al Forno Café Paragon
Yes No
Yes No Yes No
Maximum Number of Nodes in a Binary Tree
The maximum number of nodes on depth i of a binary tree is 2i, i>=0.
The maximum nubmer of nodes in a binary tree of height k is 2k+1-1, k>=0.
Prove by induction.
122 1
0
- +
k
k
i
i
Full Binary Tree
• A full binary tree of a given height k has 2k+1–1 nodes.
Height 3 full binary tree.
Labeling Nodes In A Full Binary Tree
• Label the nodes 1 through 2k+1 – 1.
• Label by levels from top to bottom.
• Within a level, label from left to right.
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Node Number Properties
• Parent of node i is node i / 2, unless i = 1.
• Node 1 is the root and has no parent.
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Node Number Properties
• Left child of node i is node 2i, unless 2i > n, where n is the number of nodes.
• If 2i > n, node i has no left child.
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Node Number Properties
• Right child of node i is node 2i+1, unless 2i+1 > n, where n is the number of nodes.
• If 2i+1 > n, node i has no right child.
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
Complete Binary Trees
A labeled binary tree containing the labels 1 to n with root 1, branches leading to nodes labeled 2 and 3, branches from these leading to 4, 5 and 6, 7, respectively, and so on.
A binary tree with n nodes and level k is complete iff its nodes correspond to the nodes numbered from 1 to n in the full binary tree of level k.
1
2 3
75
11
4
10
6
98 15141312
Full binary tree of depth 3
1
2 3
75
9
4
8
6
Complete binary tree
Binary Tree Traversals
Let l, R, 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
Inorder Traversal
• In an inorder traversal a node is visited after its left subtree and before its right subtree
Algorithm inOrder(v)
if isInternal (v)
inOrder (leftChild (v))
visit(v)
if isInternal (v)
inOrder (rightChild (v))
3
1
2
5
6
7 9
8
4
Print Arithmetic Expressions
• Specialization of an inorder traversal
• print operand or operator when visiting node
• print “(“ before traversing left subtree
• print “)“ after traversing right subtree
Algorithm inOrder (v)
if isInternal (v){print(“(’’)
inOrder (leftChild (v))}
print(v.element ())
if isInternal (v){
inOrder (rightChild (v))
print (“)’’)}+
-2
a 1
3 b ((2 (a - 1)) + (3 b))
Evaluate Arithmetic Expressions
• recursive method returning the value of a subtree
• when visiting an internal node, combine the values of the subtrees
Algorithm evalExpr(v)
if isExternal (v)
return v.element ()
else
x evalExpr(leftChild (v))
y evalExpr(rightChild (v))
operator stored at v
return x y+
-2
5 1
3 2
Creativity: pathLength(tree) = depth(v) v tree
Algorithm pathLength(v, n)
Input: a tree node v and an initial value n
Output: the pathLength of the tree with root v
Usage: pl = pathLength(root, 0);
if isExternal (v)
return n
return
(pathLength(leftChild (v), n + 1) +
pathLength(rightChild (v), n + 1) + n)
Euler Tour Traversal• Generic traversal of a binary tree
• Includes a special cases the preorder, postorder and inorder traversals
• Walk around the tree and visit each node three times:
• on the left (preorder)
• from below (inorder)
• on the right (postorder)
+
-2
5 1
3 2
L
B
R
Euler Tour TraversaleulerTour(node v) {
perform action for visiting node on the left;
if v is internal then
eulerTour(v->left);
perform action for visiting node from below;
if v is internal then
eulerTour(v->right);
perform action for visiting node on the right;
}