Trees
http://renderstuff.com/
Introduction to Trees
• Types of Data structures
– Linear
• Array, linked list
– Non Linear
• Trees, Graphs
– Choice of data Structures
• Factors
– What need to be stored
» Characteristics of data
– Cost of Operations
– Memory Consumption
– Ease of implementation
Introduction to Trees
• Non-linear data Structure
– Productivity experts say that breakthroughs come
by thinking “nonlinearly.”
– Tree structures are indeed a breakthrough in data
organization
• Allow us to implement an algorithm much faster then
using linear data structures
• The relationships in a tree are hierarchical,
– some objects being “above” and some “below” others
Introduction to Trees
• Tree Definitions
– A tree is an abstract data type that stores elements hierarchically.
• With the exception of the top element, each element in a tree has a
parent element and zero or more children.
– Logical Representation
• Natural way of storing and organizing data that is Naturally hierarchal
Introduction to Trees
• Applications of trees
A–portion
Storing Naturally
An ordered Tree Associated TRIE
of file system Tree
• book
with a Hierarchal data
– File System, GUI, Databases, Websites
– Organizing Data
• Quick search, insertion, deletion
– Binary Tree, Searching O(logn)
– Trie
• Store dictionary
– Dynamic Spell checking
Introduction to Trees
• Another Abstract Data Type
– Data structure made of nodes storing elements in a
child parents relationship
• Much like a linked list
• The difference between the two is how they are organized.
– A tree represents a hierarchical relationship between
the nodes (ancestral relationship)
• A node in a tree can have several successors, which we refer
to as children
• A nodes predecessor would be its parent
Introduction to Trees
• General Tree Information:
– Root
• Top node in a tree is called the root
• the root node has no parent above it…cuz it’s the root!
– Parent/Children
• Every node in the tree can have “children” nodes
• Each child node can, in turn, be a parent to its children and so on
– Sibling
• Children of same parents
– Leaf node
• Nodes having no children are called leaves
– Interior/internal node
• A non-leaf node is an internal/interior node
• Root is also internal node unless it is leaf node
– Ancestor
– Descendent
Introduction to Trees
• Properties of Trees:
– Recursive Data Structure
– Nodes and Edges
• N Nodes N-1 edges
– Depth of a node p
• Number of ancestors of p
• Length of path from root to node p i.e., No of edges
• If p is a root, then depth of p is ZERO,
• Otherwise, One plus the depth of it’s parent
Code Fragment 7.3: Analysis:
An algorithm to Running time: O(dp)
compute the depth of a
Worst case: O(n)
node p in a tree T .
@goodrich dp: depth of node p
Introduction to Trees
• Properties of Trees:
– Height
• Height of a node p is the Number of edges in longest path from node
p to a leaf node
– Max (depth of external nodes of p)
• The height of a tree (height of root node)
– The length of the longest path from the root to a leaf in that tree.
• A tree with only one node (the root) has a height of zero.
• If p is external, then the height of p is 0
• Otherwise, the height of p is one plus the maximum height of a
child of p
Introduction to Trees
• Properties of Trees:
– Height Algorithm
• Algorithm height1(T) for computing the height of a tree T based on
computing the maximum depth of the external nodes.
Thus,Analysis:
algorithm height2 spends O(1+ cp) time
• node
at each p, andcalls
height1 its running time is
algorithm depth(p) on
O(p(1+ ceach
p)).
external node p of T ,
Let T be
• aRunning
tree with ntimenodes,of and let c denote
height1p the
is given
number of children of a node p of T .
by O(n+∑p(1+dp)),
Then pcp =•n −n:1.number of nodes of T
Thus the running
• dp :time of algorithm
the depth of node height2,
p, and E when
is the
called on the root of T , is O(n)
set of external nodes of T .
• Worst case: the sum ∑ p(1+ dp)
is proportional to n2
Introduction to Trees
• General Tree Information:
– Root: A
– Leaf nodes: BCEHIKLM
– Interior nodes: ADFGJ
• Root is also internal node unless it is leaf node
– Height of tree?
– Depth of node J?
Tree Traversals
• Traversal of Binary Trees:
– A traversal of a tree T is a systematic way of accessing, or “visiting,” all the
nodes of T
– We need a way of zipping through a tree for searching, inserting, etc.
• But how can we do this?
• If you remember…
– Linked lists are traversed from the head to the last node
…sequentially
– Can’t we just “do that” for binary trees.?.
– NO! There is no such natural linear ordering for nodes of a tree.
– Turns out, there are THREE ways/orderings of
traversing a binary tree:
• Preorder
• Inorder
• Postorder
Tree Traversals – Depth First
• A depth-first search (DFS)
explores a path all the way to
a leaf before backtracking and
exploring another path
• For example, after searching
A, then B, then D, the search
backtracks and tries another
path from B
• Node are explored in the order
ABDEHLMNIOPCF
GJKQ
• N will be found before J
Breadth-First Traversal
• A breadth-first search (BFS)
– explores nodes nearest the root before exploring nodes further
away
– visit all the nodes at depth d before we visit the nodes at depth
d+1
• For example, after searching
A, then B, then C, the search
proceeds with D, E, F, G
• Node are explored in the
order A B C D E F G H I J K L M
NOPQ
• J will be found before N
Tree Traversals – Depth First
• Traversal of Binary Trees:
– There are 3 ways/orderings of traversing a
binary tree (all 3 are depth first search
methods):
– Pre-order traversal
• the root is visited before its left and right sub-trees.
– Post-order traversal
• the root is visited after both sub-trees.
– In-order traversal
• the root is visited between the sub-trees.
Tree Traversals – Pre-Order
• Preorder Traversal – Example 1
– the root is visited before its left and right
sub-trees
Tree Traversals – Pre-Order
• Preorder Traversal – Example 2
– the root is visited before its left and right
sub-trees
Tree Traversals – Pre-Order
• Applications:
– The preorder traversal algorithm is useful for producing a linear
ordering of the nodes of a tree where parents must always come
before their children in the ordering
Tree Traversals – Post-Order
• Post-order Traversal – Example 1
– the root is visited after both sub-trees
Tree Traversals – Post-Order
• Post-order Traversal – Example 2
– the root is visited after both sub-trees
Tree Traversals – Post-Order
• Applications – Example 7.7 @Goodrich
– we want to compute the disk space used by a directory, which is
recursively given by the sum of the following
• The size of the directory itself
• The sizes of the files in the directory
• The space used by the children directories
Fig. 7.9 @Goodrich
Tree Traversals – In-Order
• In-order Traversal – Example 1
– the root is visited between the sub-trees
Tree Traversals – In-Order
• In-order Traversal – Example 2
– the root is visited between the sub-trees
• Only applicable to binary trees
Tree Traversals
• Preorder traversal
– Is useful when we want to perform an action for a
node and then recursively perform that action for
its children,
• Post-order traversal
– Is useful when we want to first perform an action
on the descendants of a node and then perform
that action on the node
Tree Traversals
• Example
Breadth-First Traversal
Breadth-First Traversal
• Coding the Breadth-First Traversal
– Let’s say you want to Traverse and Print all nodes?
– Think about it, how would you make this happen?
SOLUTION:
1) Enqueue the root node.
2) while (more nodes still in queue) {
dequeue node (at front of queue)
Print this node (that we just dequeued)
enqueue its children (if applicable)
» left then right
…continue till no more nodes in queue
}
Binary Trees
• Binary Trees:
– A tree in which each node can have a maximum of two
children
• Each node can have no child, one child, or two children
• And a child can only have one parent
– A Recursive Binary Tree Definition
• a binary tree is either empty or consists of:
– A node r, called the root of T and storing an element
» A binary tree, called the left subtree of T
» A binary tree, called the right subtree of T
Binary Trees
• Types of Binary Trees
– Full or Proper binary tree: – Complete binary tree:
• Each node has either zero or • Every level, except possibly the
two children last, is completely filled, and all
• Every node, other than the nodes are as far left as possible.
leaves, has two children
Binary Trees
• Types of Binary Trees:
– Perfect binary tree:
– All the levels are completely filled
Properties of Binary Trees
• Properties of Binary Trees:
– The root of the tree is at level 0
– The level of any other node in the tree is one more than the level of its parent
– Max number of nodes at level i is 2i
• Total # of nodes (n) in a perfect binary tree:
n = 2h+1 – 1 (maximum)
– Height (h) of the tree:
2h+1 =n + 1
h = log(n + 1)-1
If we have 15 nodes
h = log(16)-1 = 3
• Height of Complete binary tree
– Floor(log2(n))
– No of nodes in a complete binary tree?
• Cost of operation on binary tree depends on height of the tree
– Height will be less if tree is close to perfect of complete tree
Properties of Binary Trees
• More on of Binary Trees:
– Let T be a nonempty binary tree, and let n, nE , nl and h denote the
number of nodes, number of external nodes, number of internal
nodes, and height of T , respectively. Then T has the following
properties:
1. h+ 1 ≤ n ≤ 2h+1 − 1
2. 1 ≤ nE ≤ 2h
3. h ≤ nI ≤ 2h − 1
4. log(n+ 1) − 1 ≤ h ≤ n − 1
⌊log2(n)⌋≤ h ≤ n − 1
if T is proper,
1. 2h+ 1 ≤ n ≤ 2h+1 − 1
2. h+ 1 ≤ nE ≤ 2h
3. h ≤ nI ≤ 2h − 1
4. log(n+ 1)− 1 ≤ h ≤ (n− 1)/2
⌊log2(n)⌋≤ h ≤ (n− 1)/2
Binary Trees
• More Binary Tree:
– Min height
• ⌊log2(n)⌋
– O(log2(n))
– Max height
• n-1
– O(n)
Introduction to Trees
• Balanced Tree
– Difference between left and right of each node of the tree
is no more then 1
• Height of single node: 0
• Height of empty tree: -1
• Diff= |h_lift-h_right |
Binary Tree
• Athematic expression representation
– External nodes:
• are associated with variables or constants
– Internal nodes
• associated with one of the operators +, −, ×, and /.
• its value is defined by applying its operation to the values of its children.
– Proper binary tree: two operands (two children)
– Improper: (1 Operand) unary operator e.g., -3
Expression :((((3+1)×3)/((9−5)+2))−((3×(7−4))+6)).
Inorder Traversal
• In an inorder traversal a Algorithm inOrder(T,p)
node is visited after its if p is an internal node then
left subtree and before its inOrder(T, p.left())
right subtree Print p
if p is an internal node then
inOrder(T, p.right())
6
2 8
1 4 7 9
3 5
© 2010 Goodrich, Tamassia Trees 36
Pre and Post-ordered Traversal of a binary
tree
Algorithm binaryPreorder(T, p):
Print p
if p is an internal node then
binaryPreorder(T, p.left()) {recursively traverse left subtree}
binaryPreorder(T, p.right()) {recursively traverse right subtree} 6
2 8
Non-recursive solution ??
1 4 7 9
3 5
Algorithm binaryPostorder(T, p):
if p is an internal node then
binaryPostorder(T, p.left()) {recursively traverse left subtree}
binaryPostorder(T, p.right()) {recursively traverse right subtree}
Print p
© 2010 Goodrich, Tamassia Trees 37
Print Arithmetic Expressions
• Specialization of an inorder Algorithm printExpression(T, p):
traversal if p.isExternal() then
– print operand or operator when Print p.element
visiting node
– print “(“ before traversing left else
subtree print “(”
– print “)“ after traversing right
subtree
printExpression(T, p.left())
Print p.element
+ printExpression(T, p.right())
print “)”
2 - 3 b
OUTPUT:((2 (a - 1)) + (3 b))
a 1
© 2010 Goodrich, Tamassia Trees 38
Evaluate Arithmetic Expressions
• Specialization of a postorder Algorithm evalExpr(v)
traversal if v.isExternal()
– recursive method returning return v.element()
the value of a subtree else
– when visiting an internal x evalExpr(v.left())
node, combine the values of y evalExpr(v.right())
the subtrees
operator stored at v
return x y
+
2 - 3 2
5 1
© 2010 Goodrich, Tamassia Trees 39