Chapter 5 Trees - PowerPoint PPT Presentation

1 / 126
About This Presentation
Title:

Chapter 5 Trees

Description:

LVR, LRV, VLR, VRL, RVL, RLV. Adopt convention that we traverse left before ... Postorder (LRV) Preorder (VLR) A natural correspondence between. these traversals and ... – PowerPoint PPT presentation

Number of Views:76
Avg rating:3.0/5.0
Slides: 127
Provided by: ccNct
Category:
Tags: chapter | lrv | trees

less

Transcript and Presenter's Notes

Title: Chapter 5 Trees


1
Chapter 5Trees
2
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

3
Introduction
  • Definition
  • A tree is a finite set of one or more nodes such
    that
  • There is a specially designated node called root.
  • The remaining nodes are partitioned into n?0
    disjoint sets T1, , Tn, where each of these sets
    is a tree. T1, , Tn are called hte subtrees of
    the root.

4
Introduction
  • Terms
  • Node stands for the item of information and the
    branches to other nodes
  • Degree the number of subtrees of the node
  • Leaf or terminal nodes Nodes that have zero
    degree.
  • Children The roots of the subtrees of a node X
    are the children of X. X is the parent of its
    children
  • Siblings Children of the same parent.
  • Degree of a tree the maximum degree of the nodes
    in the tree
  • The ancestor of a node are all the nodes along
    the path from the root to that node.

5
Introduction
Root
leaf
6
Introduction
Fig5.2 A sample tree
7
Introduction
  • Representation of TreesList representation
  • (A(B(E(K, L), F), C(G), D(H(M), I, J)))
  • Memory representation
  • Disadvantage
  • nodes with varying number of pointer fields

Fig5.3 List representaion of the tree of Figure
5.2
8
Introduction
Fig5.4 Possible node structuure for tree of
degree K
  • Lemma 5.1
  • If T is a k-ary tree (i.e. a tree of degree k)
    with n nodes, each having a fixed size, then n (k
    1) 1 of the nk child fields are 0, n ? 1.

9
Introduction
  • Left Child-Right Sibling representation
  • Node structure (Fig. 5.5)
  • Every node has at most one leftmost child and at
    most one closest right sibling.

Fig5.5 left child-right sibling node structure
10
Introduction
Fig5.6 Left Child - Right Sibling
representation of tree of Fig 5.2
11
Introduction
  • Representation as a degree-two tree
  • Rotate the right-sibling pointers in a left
    child-right sibling tree clockwise by 45 degrees.
    (Fig. 5.7)
  • Left child-right child trees or binary trees
    (Fig. 5.8)

12
Introduction
Fig 5.7 Left child-right child tree
representation of a tree Fig5.2
13
Introduction
A
A
A
B
B
B
left child-right sibling tree
Binary tree
tree
A
A
A
B
B
C
B
C
C
Left chile-right sibling tree
tree
Fig5.8 Tree representation
Binary tree
14
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

15
Binary Trees
  • Binary tree definition
  • A finite set of nodes that either is empty or
    consists of a root and two disjoint binary trees
    called left subtree and right subtree
  • Note
  • empty binary tree possible, but no tree with zero
    nodes
  • Distinguish between the order of children

16
Binary Trees
A
A
B
B
Fig5.9 Two different binary trees
17
Binary Trees
Skewed
Complete
Level 1 2 3 4 5
B
B
C
D
E
G
D
I
H
(a)
(b)
E
Fig5.10 skew and comple binary tree
18
Binary Trees
  • Properties of Binary Trees
  • Lemma 5.2 Maximum number of nodes
  • The maximum number of nodes on level i of a
    binary tree is 2i-1, i ? 1.
  • The maximum number of nodes in a binary tree of
    depth k is 2k - 1, k ? 1.
  • Lemma 5.3 Relation between number of leaf nodes
    and degree-2 nodes
  • For any nonempty binary tree, T, if n0 is the
    number of leaf nodes and n2 the number of nodes
    of degree 2, then n0 n2 1.

19
Binary Trees
  • Definition
  • A full binary tree of depth k is a binary tree of
    depth k having 2k-1 nodes, kgt 0
  • Definition
  • A binary tree with n nodes and depth k is
    complete iff its nodes correspond to the nodes
    numbered from 1 to n in the full binary tree of
    depth k

20
Binary Trees
Fig5.11 Full binary tree of Depth 4 with
sequential node numbers
21
Binary Trees
  • Array representation
  • Use a one-dimensional array to represent the
    nodes numbered from 1 to n as shown in Fig 5.11
  • Lemma 5.4
  • If a complete binary tree with n nodes is
    represented sequentially, then for any node with
    index i, 1 ? i ? n, we have
  • parent(i) is at ?i/2? if i ? 1. If i 1, i is at
    the root and has no parent.
  • LeftChild(i) is at 2i if 2i ? n. If 2i gt n, then
    i has no child.
  • RightChild(i) is at 2i 1 if 2i 1 ? n. If 2i 1
    gt n, then i has no right child.

22
Binary Trees
1 2 3 4 5 6 7 8 9
Fig5.12 array representation of the binary
trees of Fig5.10
23
Binary Trees
  • Linked representation (Fig. 5.13, 5.14)
  • class Tree //forward declaration
  • class TreeNode
  • friend class Tree
  • private
  • TreeNode LeftChild
  • char data
  • TreeNode RightChild

class Tree public //Tree operation
private TreeNode root
LeftChild data RightChild
Fig5.13 Node representaion
24
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

25
Binary tree traversal and tree Iterators
  • Binary tree traversal and tree Iterators
  • Traversing a tree of visiting each node in the
    tree exactly once
  • When a node is visited, some operation (e.g.
    output data field) is performed
  • A full traversal produce a linear order for the
    nodes in a treed
  • There are six possible combinations of traversal
  • LVR, LRV, VLR, VRL, RVL, RLV
  • Adopt convention that we traverse left before
    right, only 3 traversals remain
  • Inorder (LVR)
  • Postorder (LRV)
  • Preorder (VLR)
  • A natural correspondence between
  • these traversals and
  • producing infix, postfix, and prefix forms of an
    expression.

26
Binary tree traversal and tree Iterators
inorder traversal A / B C D E preorder
traversal / A B C D E postorder
traversal A B / C D E level order
traversal E D / C A B
Fig5.16 Binary tree with arithmetic expression
27
Binary tree traversal and tree Iterators
  • Inorder traversal
  • Moving down the tree toward the left until you
    can go no farther.
  • Visit the node
  • Move to the right .
  • If you cannot move to the right, go back one more
    node.
  • Preorder traversal
  • Visit a node, traverse left, and continue.
  • When you cannot continue, move right and begin
    again or move back until you can move right and
    resume.

28
Binary tree traversal and tree Iterators
  • void Tree inorder() (prog5.1)
  • // Driver calls workhorse for traversal of entire
    tree. The driver is
  • // declared as a public member function of Tree.
  • inorder(root)
  • void Tree inorder(TreeNode CurrentNode)
  • // Workhorse traverses the subtree rooted at
    CurrentNode
  • // The workhorse is declared as a private member
    function of Tree.
  • if(CurrentNode)
  • inorder(CurrentNode ? LeftChild)
  • cout ltlt CurrentNode ? data
  • inorder(CurrentNode ? RightChild)
  • Look Fig5.17

29
Binary tree traversal and tree Iterators
Fig5.17trace of prog5.1
30
Binary tree traversal and tree Iterators
  • void Tree preorder() (prog5.2)
  • // Driver calls workhorse for traversal of entire
    tree. The driver is
  • // declared as a public member function of Tree.
  • preorder(root)
  • void Tree preorder(TreeNode CurrentNode)
  • // Workhorse traverses the subtree rooted at
    CurrentNode
  • // The workhorse is declared as a private member
    function of Tree.
  • if(CurrentNode)
  • cout ltlt CurrentNode ? data
  • preorder(CurrentNode ? LeftChild)
  • preorder(CurrentNode ? RightChild)

31
Binary tree traversal and tree Iterators
  • Postorder traversal (prog5.3)
  • void Tree postorder()
  • // Driver calls workhorse for traversal of entire
    tree. The driver is
  • // declared as a public member function of Tree.
  • postorder(root)
  • void Tree postorder(TreeNode CurrentNode)
  • // Workhorse traverses the subtree rooted at
    CurrentNode
  • // The workhorse is declared as a private member
    function of Tree.
  • if(CurrentNode)
  • postorder(CurrentNode ? LeftChild)
  • postorder(CurrentNode ? RightChild)
  • cout ltlt CurrentNode ? data

32
Binary tree traversal and tree Iterators
  • Iterator inorder traversal
  • Tree is a container class
  • Implement tree traversal by using iterator
  • Need nonrecursive tree traversal

33
Binary tree traversal and tree Iterators
  • Iterative inorder traversal(prog5.4)
  • void Tree NonrecInorder()
  • // nonrecursive inorder traversal using a stack
  • Stack ltTreeNode gt s // declare and
    initialize stack
  • TreeNode CurrentNode root
  • while(1)
  • while (CurrentNode) //move down
    LeftChild fields
  • s.Add(CurrentNode) //add to stack
  • CurrentNode CurrentNode ?
    LeftChild
  • if(!s.IsEmpty()) // stack is not empty
  • CurrentNode s.Delete ( CurrentNode
    ) // delete from stack
  • cout ltlt CurrentNode ? data ltlt endl
  • CurrentNode CurrentNode ?
    RightChild
  • else break

34
Binary tree traversal and tree Iterators
  • Class InorderIterator (prog 5.5)
  • Public
  • Char Next()
  • I norderIterator(Tree tree)t(tree)CurrentNodet.
    root
  • Private
  • Const Tree t
  • StachltTreeNodegt s
  • TreeNode CurrentNode

35
Binary tree traversal and tree Iterators
  • Char InorderIteratorNext()(prog5.6)
  • While(CurrentNode)
  • S.Add(CurrentNode)
  • CurrentNodeCurrentNode-gtLeftChild
  • If(!d.IdEmpty())
  • CurrentNodes.Delete(CurrentNode)
  • Char tempCurrentNode-gtdata
  • CurrentNodeCurrentNode-gtRightChild//update
    CurrentNode
  • return temp
  • else return 0

36
Binary tree traversal and tree Iterators
  • Level-order traversal(prog5.7)
  • void Tree LevelOrder ()
  • // Traverse the binary tree in level order
  • Queue lt TreeNode gt q
  • TreeNode CurrentNode root
  • while (CurrentNode)
  • cout ltlt CurrentNode ? data ltlt endl
  • if (CurrentNode ? LeftChild) q.Add
    (CurrentNode ? LeftChild )
  • if (CurrentNode ? RightChild) q.Add
    (CurrentNode ? RightChild )
  • CurrentNode q.Delete (CurrentNode)

37
Binary tree traversal and tree Iterators
  • Is binary tree traversal possible without the use
    of extra space for a stack?
  • Solution I
  • Add a parent field to each node
  • Solution II
  • Represent as threaded binary tree

38
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

39
Additional Binary Tree Operations
  • Copying binary trees
  • Modify version of postorder
  • Testing for equality of binary trees
  • Equivalent binary trees have the same structure
    and the same information in the corresponding
    nodes

40
Additional Binary Tree Operations
  • // Copy constructor (prog5.9)
  • Tree Tree (const Tree s) // driver
  • root copy (s.root)
  • TreeNode Tree copy(TreeNode orignode) //
    Workhorse
  • // This function returns a pointer to an exact
    copy of the binary tree
  • rooted at orignode.
  • if (orignode)
  • TreeNode temp new TreeNode
  • temp ? data orignode ? data
  • temp ? LeftChild copy (orignode ?
    LeftChild)
  • temp ? RightChild copy (orignode ?
    RightChild)
  • return temp
  • else return 0

41
Additional Binary Tree Operations
  • // Driver assumed to be a friend of class Tree.
    (pro5.10)
  • int operator(const Tree s, const Tree t)
  • return equal (s.root, t.root)
  • //Workhorse assumed to be a friend of TreeNode.
  • int equal (TreeNode a, TreeNode b)
  • // This function returns 0 if the subtrees at a
    and b are not equivalent.
  • // Otherwise, it will return 1.
  • if ( (!a) (!b) ) return 1 // both a and b
    are 0
  • if ( a b // both a and b are non-0
  • (a?data b?data) // data is the
    same
  • equal (a?LeftChild, b?LeftChild) //
    left subtrees are the same
  • equal (a?RightChild, b?RightChild)
    // right subtrees are the same
  • return 1
  • return 0

42
Additional Binary Tree Operations
  • The formulas of the propositional calculus
  • (1) A variable is an expression.
  • (2) If x and y are expressions then x ? y, x ? y,
    and ?x are expressions.
  • (3) Parentheses can be used to alter the normal
    order of evaluation, which is not before and
    before or.
  • Example x1 ? (x2 ? ?x3 )
  • The satisfiability problem
  • If there is an assignment of values to the
    variables that causes the value of the expression
    to be true?
  • The most obvious algorithm 2n possible
    combinations

43
Additional Binary Tree Operations
(x1 ? x2) ? ( x1 ? x3) ? x3
?
?
?
?
X3
?
X3
?
?
X1
X2
X1
Fig5.18Propositional formula in a binary tree
44
Additional Binary Tree Operations
  • enum Boolean FALSE, TRUE
  • enum TypesOfData LogicalNot, LogicalAnd,
    LogicalTrue, LogicalFalse
  • class SatTree //forward declaration
  • class SatNode
  • friend class SatTree
  • private
  • SatNode LeftChild
  • TypesOfData data
  • Boolean value
  • SatNode RightChild
  • class SatTree
  • public
  • void PostOrderEval ()
  • void rootvalue () cout ltlt root?value
  • private
  • SatNode root
  • void PostOrderEval (SatNode )

45
Additional Binary Tree Operations
  • for all 2n possible combinations for the n
    variables
  • generate the next combination
    replace the variables by their values
    evaluate the formula by traversing the tree
    itpoints to in postorder if
    (formula.rootvalue())
    coutltltcombination return coutltltNo
    satisfiable combination

Prog5.11
46
Additional Binary Tree Operations
  • void SatTree PostOrderEval (SatNode s)
    //Workhorse (prog5.12)
  • if (s)
  • PostOrderEval ( s?LeftChild)
  • PostOrderEval ( s?RightChild)
  • switch (s?data)
  • case LogicalNot s?value ! s?RightChild
    ?value break
  • case LogicalAnd s?value ! s?LeftChild
    ?value

  • s?RightChild ?value
  • break
  • case LogicalOr s?value s ?LeftChild
    ?value s?RightChild ?value
  • break
  • case LigicalTrue s?value TRUE break
  • case LogicalFalse s?value FALSE

47
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

48
Threaded Binary Tree
  • Threads
  • For a binary tree with n nodes
  • number of non-null links n-1total links
    2nnull links 2n-(n-1)n1
  • To replace the 0-links by pointers, called
    threads, to other nodes in the tree.
  • A 0 RightChild field in a node p is replaced by
    the inorder successor of p.
  • A 0 LeftChild link at node p is replaced by the
    inorder predecessor of

49
Threaded Binary Tree
root
inorder traversal H, D, I, B, E, A, F, C, G
Fig5.20Threaded tree corresponding to
Figure5.10(b)
50
Threaded Binary Tree
LeftThread LeftChild data
RightChild RightThread
?
?
TRUE
Fig5.21 An empty threaded binary tree
51
Threaded Binary Tree
  • class ThreadedNode
  • friend class ThreadedTree
  • friend class ThreadedInorderIterator
  • private
  • Boolean LeftThread
  • ThreadedNode LeftChild
  • char data
  • ThreadedNode RightChild
  • Boolean RightThread

52
Threaded Binary Tree
Fig5.22 Memory Representation of a Threaded Tree
53
Threaded Binary Tree
  • Finding the inorder successor
    traversal(prog5.14)
  • char ThreadedInorderIterator Next()
  • // Find the inorder successor of CurrentNode in a
    threaded binary tree
  • ThreadedNode temp CurrentNode ? RightChild
  • if (! CurrentNode ? RightThread )
  • while ( ! Temp ? LeftThread ) temp temp ?
    LeftChild
  • CurrentNode temp
  • if ( CurrentNode t.root ) return 0
  • else return CurrentNode ? data

54
Threaded Binary Tree
  • Finding the inorder successor
    traversal(prog5.15)
  • void ThreadedInorderIterator Inorder()
  • for ( char ch Next() ch chNext() )
  • cout ltlt ch ltlt endl

55
Threaded Binary Tree
Insert a node D as a right child of B.
root
root
(1)
s
s
(3)
r
r
C
(2)
empty
(a)
Fig2.3Insertion of r as a right child of s in a
threaded binary tree
56
Threaded Binary Tree
s
s
(3)
r
r
(1)
(2)
(4)
(b)
Fig2.3Insertion of r as a right child of s in a
threaded binary tree
57
Threaded Binary Tree
  • Inserting a node into a threaded binary tree
    (pro5.16)
  • void ThreadedTree InsertRight ( ThreadedNode
    s, ThreadedNode r)
  • // Insert r as the right child of s
  • r ? RightChild s ? RightChild
  • r ? RightThread s ? RightThread
  • r ? LeftChild s
  • r ? LeftThread TRUE // LeftChild is a
    thread
  • s ? RightChild r // attach r to s
  • s ? RightThread FALSE
  • if ( ! r ? RightThread )
  • ThreadedNode temp InorderSucc (r)
  • // returns the inorder successor of r
  • temp ? LeftChild r

58
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • Heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

59
Heaps
  • Priority queues (Heaps are frequently used)
  • The element to be deleted is the one with highest
    (or lowest) priority.
  • At any time, an element with arbitrary priority
    can be inserted into the queue
  • Max (min) priority queue.
  • template ltclass Typegt
  • class MaxPQ
  • public
  • virtual void Insert (const Element ltType gt)
    0
  • virtual Element ltTypegt DeleteMax (Element ltType
    gt) 0

60
Heaps
  • Example 5.1 Selling the services of a machine.
  • Each user pays a fixed amount per use.
  • The time needed by each user is different.
  • Maximize the returns.
  • The user with the smallest time requirement is
    selected.
  • Example 5.2 Simulating a large factory.
  • There are many machines.
  • Many jobs require processing on some machines.
  • An event to occur whenever a machine completes
    the processing of a job.
  • When an event occurs,

61
Heaps
  • A max tree is a tree in which the key value in
    each node is no smaller than the key values in
    its children. A max heap is a complete binary
    tree that is also a max tree. (Fig 5.24)
  • A min tree is a tree in which the key value in
    each node is no larger than the key values in
    its children. A min heap is a complete binary
    tree that is also a min tree.(Fig 5.25)
  • Operations on heaps
  • creation of an empty heap(prog5.17)
  • insertion of a new element into the heap
    (prog5.18)
  • deletion of the largest element from the
    heap)(prog5.19)

62
Heaps
4
Fig 5.24 Sample max heaps
63
Heaps
Fig 5.26Sample min heaps
64
Heaps
  • MaxHeap MaxHeap(int sz DefaultSize)(prog5.17)
  • Maxsizesz
  • n0
  • Heapnew ElementltTypegtMaxSize1 //heap0 is
    not used

65
Heaps
1
1
3
2
3
2
5
5
4
5
6
4
add 5
5
2
21
1
1
3
3
2
2
20
5
5
4
4
6
add 21
21
2
Fig5.26 Insertion into a max heap
66
Heaps
  • Insertion into a Max Heap O(log n) (prog. 5.18)
  • template ltclass Typegt
  • void MaxHeapltTypegt Insert(const Element ltTypegt
    x)
  • // insert x into the max heap
  • if (nMaxSize) HeapFull() return
  • n
  • for (int in 1)
  • if (i1) break // at root
  • if (x.key lt heap i/2.key) break
  • // move from parent to i
  • heap i heap i/2
  • i /2
  • heap i x

67
Heaps
Fig5.27 Deletion from a heap
68
Heaps
  • Deletion from a Max Heap O(log n) (prog5.19)
  • template ltclass Typegt
  • Element ltTypegt MaxHeap ltTypegt DeleteMax
    (Element ltTypegt x)
  • // Delete from the max heap
  • if (!n) HeapEmpty() return 0
  • x heap 1 Element ltTypegt k heap n n--
  • for (int i 1 j2 jltn)
  • if (jltn) if (heap j.key lt heap j1.key)
    j
  • // j points to the larger child
  • if (k.key gt heap j.key ) break
  • heap i heap j // move child up
  • i j j2 // move i and j down
  • heap i k
  • return x

69
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

70
Binary Search Trees
  • Binary search tree A binary tree. (Fig. 5.28)
  • Every element has a key and no two elements have
    the same key.
  • The keys in the left subtree are smaller than the
    key in the root.
  • The keys in the rightn subtree are larger than
    the key in the root.
  • The left and right subtrees are also binary
    search trees.
  • The search, insert, and delete can be performed
  • By key value
  • By rank

71
Binary Search Trees
Fig5.28 Binary Tree
72
Binary Search Trees
  • Recurrsive search of a BST (prog5.20)
  • template ltclass Typegt //Driver
  • BstNode ltTypegt BST ltTypegt Search (const
    Element ltTypegt x)
  • // Search the binary search tree (this) for and
    element with key x.
  • // If such an element si found, return a pointer
    to the node that contains it.
  • return Search (root, x)
  • template ltclass Typegt // Workhorse
  • BstNode ltTypegtBST ltTypegtSearch (BstNode ltTypegt
    b,

  • const Element ltTypegt x)
  • if (!b) return 0
  • if (x.key b ? data.key) return b
  • if (x.key lt b ? data.key) return Search (b ?
    LeftChild, x)
  • return Search (b ?RightChild, x)

73
Binary Search Trees
  • Iterative search of a BST (prog5.21)
  • template ltclass Typegt
  • BstNode ltTypegt BST ltTypegt IterSearch (const
    Element ltTypegt x)
  • // Search the binary search tree for an element
    with key x.
  • for( BstNode ltTypegt t root t )
  • if (x.key t ? data.key) retury t
  • if ( x.key lt t ? data.key) t t ? LeftChild
  • else tt ? RightChild
  • return 0

74
Binary Search Trees
  • Searching a BST by rank
  • template ltclass Typegt
  • BstNode ltTypegt BST ltTypegt Search(int k)
  • // Search the binary search tree for the kth
    smallest element
  • BstNode ltTypegt t toot
  • while (t)
  • if ( kt ? LeftSize) return t
  • if ( kltt ? LeftSize) tt ? LeftChild
  • else
  • k-LeftSize
  • t t ? RightChild
  • return 0

75
Binary Search Trees
Fig5.29 Inserting into a Binary Search Tree
76
Binary Search Trees
  • template ltclass Typegt (pro5.23)
  • Boolean BST ltTypegt Insert (const Element
    ltTypegt x)
  • // Insert x into the binary search tree
  • // Search for x.key, q is parent of p
  • BstNode ltTypegt p root BstNode ltTypegt q
    0
  • while (p)
  • qp
  • if (x.key p ? data.key) return FALSE //
    x.key is already in tree
  • if (x.key lt p ? data.key) pp ? LeftChild
  • else pp ? RightChild
  • // Perform insertion
  • p new BstNode ltTypegt
  • p ? LeftChild p ? RightChild 0 p ? data
    x
  • if (!root) root p
  • else if (x.keyltq ?data.key) q ? LeftChild p
  • else q ?RightChild p
  • return TRUE

77
Binary Search Trees
  • Deletion from a BST O(log h) (Fig. 5.30)
  • Deletion of a leaf element is quite easy.
  • Deletion of a nonleaf element that has only one
    child is also easy.
  • Deletion of a nonleaf node that has two children
  • The element is replaced by either the largest
    element in its left subtree, or the smallest one
    in its right subtree.

78
Binary Search Trees
  • Joining binary trees
  • C.ThreeWayJoin(A, x, B)
  • Each element in A has a smaller key than x.key.
  • Each element in B has a larger key than x.key.
  • C.TwoWayJoin(A, B)
  • All keys of A are smaller than all keys of B.
  • Split binary tree
  • A.Split(i, B, x, C)
  • B is a BST that contains all elements of A that
    have key less than i

79
Binary Search Trees
  • Splitting a BST(prog5.24)
  • template ltclass Typegt Element ltTypegt
  • Element ltTypegt BST ltTreegt Split (Type i,
    BSTltTypegtB,

  • ElementltTypegtx,

  • BSTltTypegtC)
  • // Split the binary tree with respect to key i
  • if (!root) B.root C.root 0 return 0 //
    empty tree
  • // create head nodes for B and C
  • BstNode ltTypegt Y new BstNode ltTypegt BstNode
    ltTypegt LY
  • BstNode ltTypegt Z new BstNode ltTypegt BstNode
    ltTypegt RZ
  • BstNode ltTypegt t root

80
Binary Search Trees
  • while (t)
  • if (i t?data.key) // split at t
  • L ?RightChild t ?LeftChild
  • R ?Leftchild t ?RightChild
  • x t ?data
  • B.root Y ?RightChild delete Y
  • C.root Z ?LeftChild delete Z
  • return x
  • else if ( iltt ?data.key)
  • R ?Leftchild t
  • R t tt ?LeftChild
  • else
  • L?Rightchild t
  • L t t t ?rightChild

81
Binary Search Trees
  • // Set 0 pointers and delete head nodes
  • L ?RightChild R ?LeftChild 0
  • B.root Y ?RightChild delete Y
  • C.root Z ?LeftChild delete Z
  • return 0

82
Binary Search Trees
  • Height of a Binary Search Tree
  • Worst case
  • The height of a binary search tree with n
    elements can as large as n
  • insert keys 1, 2, ..., n in that order
  • On the average
  • O(log2n)
  • insertion and deletion are made at random
  • Balanced search trees
  • Search trees with a worst case height of O(log2n)
  • Permit searches, insertions, and deletions in
    O(h)
  • AVL, 2-3, and red-black trees

83
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

84
Selection Trees
  • Suppose we k ordered sequences, called runs.
  • Let n be the number of records in all k runs
    together.
  • We want to merge all these k runs into a single
    ordered sequence.
  • Solution 1
  • Repeatedly output the record with smallest key by
    comparing the leading record in any of k-runs
  • O(kn), n is the total number of records in the
    k-runs
  • Solution 2
  • We may achieve the result by finding the next
    smallest element by using the data structure
    selection tree.
  • There are two kinds of selection trees
  • Winner trees
  • Loser tree

85
Selection Trees
  • Winner tree (Fig. 5.31)
  • A complete binary tree in which each node
    represents the smaller of its two children.
  • The root node represents the smallest node in the
    tree.
  • Each leaf node represents the first record in the
    corresponding run.
  • If the record pointed to by the root is output,
    we need to restructure the tree.
  • The tournament is played between sibling nodes
    and the result put in the parent node. (Fig.
    5.32)
  • Complexity of merging O(n log2 k)
  • Each time to restructure the tree is O(log2k)
  • The number of levels in the tree is ceiling
    log2(k 1)

86
Selection Trees
1
6
3
2
8
6
7
4
5
6
17
8
6
9
11
12
13
15
9
10
8
14
9
6
8
17
9
20
90
10
95
99
28
run 8
run 6
run 7
run 5
run 4
run 2
run 3
run 1
Fig5.31 winner tree for k8, showing the first
three keys in each of the eight runs
87
Selection Trees
Figure 5.32 Winner tree of Figure 5.31 after one
record has been output and the tree
restructured(nodes that were changed are ticked)
88
Selection Trees
overall winner
6
Run 1 2 3 4
5 6 7 8
Figure 5.33 Loser tree corresponding to winner
tree of Figure 5.31
89
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

90
Forests
  • Forest
  • A forest is a set of n gt 0 disjoint trees

Forest
G
E
A
I
H
F
D
C
B
Figure 5.34 Three-tree forest
91
Forests
  • Transform a forest into a binary tree
  • If T1, T2, , Tn a forest of treesB(T1, T2, ,
    Tn) a binary tree corresponding to this forest
  • algorithm(1) empty, if n 0(2) has root equal
    to root(T1) has left subtree equal to
    B(T11,T12,,T1m) where T11,T12,,T1m are the
    subtrees of root(T1) and has right subtree
    B(T2,T3,,Tn)

92
Forests
A
B
E
G
F
C
H
D
I
Fig3.35Binary Tree representation of forest of
Figure5.43
93
Forests
  • Forest Traversals
  • Preorder
  • If F is empty, then return
  • Visit the root of the first tree of F
  • Taverse the subtrees of the first tree in tree
    preorder
  • Traverse the remaining trees of F in preorder
  • Inorder
  • If F is empty, then return
  • Traverse the subtrees of the first tree in tree
    inorder
  • Visit the root of the first tree
  • Traverse the remaining trees of F is indorer

94
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

95
Set Representation
  • Assumption
  • Elements of the sets are the numbers 0, 1, . . .,
  • n-1
  • Sets being represented are pairwise disjoint
  • Possible forest representation of sets (Fig.
    5.36)
  • Linking the nodes from children to parent
  • Operations performing on these sets
  • Disjoint set union
  • Find(i) find the set containing the element, i

96
Set Representation
Fig5.36
  • S10, 6, 7, 8, S21, 4, 9, S32, 3, 5
  • Two operations considered here
  • Disjoint set union S1 ? S20,6,7,8,1,4,9
  • Find(i) Find the set containing the element
    i. 3 ? S3, 8 ? S1

97
Set Representation
4
0
9
1
0
4
8
7
6
8
7
6
9
1
Fig 5.37 Possible representation for S1 union S2
98
Set Representation
4
1
9
2
3
5
Figure 5.38 Data Representation of S1S2and S3
99
Set Representation
Fig5.39 Array representaion of S1 S2, and S3 of
Figure 5.36
100
Set Representation
  • Class Sets (prog5.25)
  • Public
  • //Set operation follow
  • ...
  • Private
  • int parent
  • Int n//number of setelements
  • SetSet(int szHeapSize)
  • nsz
  • Parent new int sz
  • For(int i0iltni) parenti -1

101
Set Representation
  • Void SetsSimpleUnion(int i,int j) (prog5.26)
  • //Replace the disjoint sets with roots i and
    j,i!j with their union
  • parenti j
  • Int SetsSimpleFind(int i)
  • //Find the root of the tree containing element i
  • while(parentigt0) i parenti
  • return i

102
Set Representation
n-1
n-2
? ? ?
0
Fig5.40Degenerate tree
103
Set Representation
  • Weighting rule for union(i,j)
  • If number of nodes in tree i is less than the
    number in the tree with root j, then make j the
    parent of i otherwise, make i the parent of j
  • Add additional field indicating number of nodes
    in the set at root of tree parent(i) as -count

104
Set Representation
105
Set Representation
  • Void SetsWeightedUnion (int i, int j)(prog5.27)
  • int temp parentiparentj
  • if (parentigtparentj)
  • parentij
  • parentjtemp
  • else
  • parentji
  • parentitemp

106
Set Representation
  • Lemma 5.5
  • Assume that we start with a forest of trees,each
    having one node.Let T be a tree
  • with m nodes created as a result of a sequence
    of uniobs each performed using function
    WeightedUnion. The height of T is no greater than
    log2m1
  • Definition Collapsing rule
  • If j is a node on the path from I to its root
    and parenti
  • ?root(i),then set parentj to root(i)

107
Set Representation
108
Set Representation
109
Set Representation
  • Int SetsCollapsingFind(int i)(Prog 5.28)
  • for (ri parentrgt0 rparent)
  • while(i!r)
  • int s parenti
  • parenti r
  • is
  • return r

110
Set Representation
111
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

112
An object-oriented system of tree data structures
BinaryTree
SearchStruct
CompleteBinaryTree
BST
MaxPQ
MaxHeap
Winner
Fig5.44 Inheritance graph showing the
relationship between different ADTs
113
An object-oriented system of tree data structures
  • enum BooleanFALSE,TRUE(prog. 5.29)
  • Const int DefaultSize 20
  • Class MaxPQ
  • public
  • Virtual void insert(const int) 0 //pure
    virtual functions
  • Virtual int DeleteMaz(int ) 0
  • Class SearchStruct
  • Public
  • Virtual void insert(const int ) 0 //pure
    virtual functions
  • Virtual int Delete(int) 0
  • Virtual Boolean Search(const int) 0

114
An object-oriented system of tree data structures
  • Class BinaryTree
  • Public
  • Virtual void inorder()//driver
  • BinaryTree()root0//constructor
  • Protected
  • Class BinaryTreeNode//nested class
  • Public
  • BinaryTreeNode LeftChild,RightChild
  • Int data
  • BinaryTreeNode root
  • Virtual void inorder(BinaryTreeNode)//workhorse

115
An object-oriented system of tree data structures
  • Class CompleteBinaryTreepublic
    BinaryTree(Prog5.30)
  • Public
  • Virtual void inorder()
  • CompleteBinaryTree(int szDefaultSize)MazSize(sz)
    ,n(0)
  • Treenew int MaxSize1
  • Class MaxHeappublic MaxPQ,public
    CompleteBinaryTree
  • Public
  • MaxHeap(int szDefaultSize)CompleteBinaryTree(sz)
  • virtual void insert(const int)
  • Virtual int DeleteMax(int )

116
An object-oriented system of tree data structures
  • Class WinnerTreepublic CompleteBinaryTree
  • Public
  • WinnerTree(int szDefaultSize)CompleteBinaryTree(
    sz)
  • Class BSTpublic SearchStruct,public BinaryTree
  • Public
  • BST()root0
  • Virtual void insert(const int)
  • Virtual int Delete(int)
  • Virtual Boolean Search(const int)

117
Trees
  • Introduction
  • Binary trees
  • Binary Tree Traversal and Tree Iterators
  • Addtional Binary Tree Operations
  • Threaded Binary Tree
  • heaps
  • Binary search tree
  • Selection trees
  • Forests
  • Set representation
  • An object-oriented system of tree data structures
  • Counting Binary Trees

118
Counting Binary Trees
  • Counting Binary Trees
  • Determine the number of distinct binary trees
    having n nodes
  • n2 (Fig5.45)
  • n3 (Fig5.46)
  • Distinct binary trees
  • Stack permutations and Matrix multiplication
  • Using Inorder and Preorder sequences
  • Example (Fig5.47,Fig5.48)
  • Preorder sequence ABCDEFGHI
  • Inorder sequence BCAEDGHFI

119
Counting Binary Trees
Fig 5.45 Distinct binary trees with n2
120
Counting Binary Trees
Fig5.46 Distinct Binary trees with n3
121
Counting Binary Trees
A
A
D, E, F, G, H, I
D, E, F, G, H, I
B, C
B
(a)
C
(b)
Fig5.47 Constructing a binary tree from its
inorder and preorder sequences
122
Counting Binary Trees
1
A
4
2
D
B
3
5
6
C
E
F
7
9
G
I
(b)
(a)
8
H
Fig5.48 Binary tree constructed from its
inorder and preorder sequences
123
Counting Binary Trees
  • stack permutation
  • Every binary tree has a unique pair of
    preorder/inorder sequences
  • Trees its preorder permutation is 1, 2, , n,
    then distinct binary trees is equal to the number
    of distinct inorder permutations
  • Stack permutation
  • Passing the numbers 1 to n through a stack and
    deleting in all possible ways
  • of stack permutation of inorder permutation

124
Counting Binary Trees
  • Preorder (1, 2, 3)
  • Possible permutations obtainable by a stack are
  • (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3,
    2, 1)
  • (3, 1, 2) is impossible
  • Five distinct binary trees, n 3

1
1
1
1
1
2
2
2
3
2
2
3
3
3
3
125
Counting Binary Trees
  • Matrix multiplication
  • M1M2. . . Mn
  • matrix multiplication is associative,we can
    perform these multiplications in any order
  • Examples
  • n 3, (M1M2)M3 , M1(M2M3)
  • n 4, ((M1M2)M3)M4
  • (M1(M2M3))M4
  • M1((M2M3)M4)
  • (M1(M2(M3M4)))
  • ((M1M2)(M3M4))

126
Counting Binary Trees
  • matrix multiplication(n1) inorder
    permutation
  • of stack permutation

bn
bi
bn-i-1
Fig5.50Decomposing bn
Write a Comment
User Comments (0)
About PowerShow.com