+ All Categories
Home > Documents > Gordon College Prof. Brinton

Gordon College Prof. Brinton

Date post: 11-Feb-2016
Category:
Upload: freira
View: 31 times
Download: 0 times
Share this document with a friend
Description:
Binary Trees. Gordon College Prof. Brinton. Good O’ Linear Search. Collection of data items to be searched is organized in a list x 1 , x 2 , … x n Must assume = = and < operators defined for the type Linear search begins with item 1 continue through the list until target found - PowerPoint PPT Presentation
52
1 Binary Trees Gordon College Prof. Brinton
Transcript
Page 1: Gordon College Prof. Brinton

1

Binary Trees

Gordon CollegeProf. Brinton

Page 2: Gordon College Prof. Brinton

2

Good O’ Linear Search

• Collection of data items to be searched is organized in a list x1, x2, … xn

Must assume = = and < operators defined for the type

• Linear search begins with item 1– continue through the list until target found– or reach end of list

Not sorted

Page 3: Gordon College Prof. Brinton

3

Linear Search

Vector based search functiontemplate <typename t>void LinearSearch (const vector<t> &v, const t &item, boolean &found, int &loc){ found = false; loc = 0; for ( ; ; ){ if (found || loc == v.size()) return; if (item == x[loc]) found = true; else loc++; }} usage

LinearSearch(vect,num,found,loc);

Page 4: Gordon College Prof. Brinton

4

Linear Search

Singly-linked list based search functiontemplate <typename t>void LinearSearch (NodePointer first, const t &item, boolean &found, int &loc){ found = false; locptr = first; for ( ; ; ){ if (found || locptr == NULL) return; if (item == locptr->data) found = true; else loc++; }}

In both cases, the worst case computing

time is still O(n)

Page 5: Gordon College Prof. Brinton

5

Binary SearchBinary search function for vector

template <typename t>void LinearSearch (const vector<t> &v, const t &item, boolean &found, int &loc)

{ found = false; int first = 0; last = v.size() - 1; for ( ; ; ){ if (found || first > last) return; loc = (first + last) / 2; if (item < v[loc]) last = loc + 1; else if (item > v[loc]) first = loc + 1; else /* item == v[loc] */ found = true; }

}

Sortedvector

Page 6: Gordon College Prof. Brinton

6

Binary Search

• Usually outperforms a linear search• Disadvantage:

- Only appropriate for direct access structures like vectors - not linked lists (Why?)

• It is possible to use a linked structure which can be searched in a binary-like manner

Page 7: Gordon College Prof. Brinton

7

Binary Search Tree

• Consider the following ordered list of integers

1. Examine middle element2. Examine left, right sublist (maintain pointers)3. (Recursively) examine left, right sublists

80666249352813

Page 8: Gordon College Prof. Brinton

8

Binary Search Tree

• Redraw the previous structure so that it has a treelike shape – a binary tree

Page 9: Gordon College Prof. Brinton

9

Trees

• A data structure which consists of – a finite set of elements called nodes or vertices– a finite set of directed arcs which connect the

nodes• If the tree is nonempty

– one of the nodes (the root) has no incoming arc– every other node can be reached by following a

unique sequence of consecutive arcs

Page 10: Gordon College Prof. Brinton

10

Trees

• Tree terminology Root node

Leaf nodes

• Children of the parent (3)

• Siblings to each other

Interior nodes

Page 11: Gordon College Prof. Brinton

11

Trees

• More Tree Terms

Each node in treeis the root of aSubtree

Recursive?

• The depth of a node n is the length of the path from the root to the node. • The height of a tree is the depth of its furthest leaf. •Siblings are nodes that share the same parent node.• If a path exists from node p to node q, where node p is closer to the root node than q, then p is an ancestor of q and q is a descendant of p.• The size of a node is the number of descendants it has including itself. • In-degree of a vertex is the number of edges arriving at that vertex.• Out-degree of a vertex is the number of edges leaving that vertex.

Page 12: Gordon College Prof. Brinton

12

Tree LevelsA

HG

FE

DCB

Level: 0

Level: 1

Level: 2

Level: 3

Page 13: Gordon College Prof. Brinton

13

Binary Trees• Each node has at most two children• Useful in modeling processes where

– a comparison or experiment has exactly two possible outcomes

– the test is performed repeatedly• Examples

– multiple coin tosses– Expert systems (yes/no questions)– encoding/decoding messages in dots and dashes such

as Morse code– Expression tree (compiler generates)

Page 14: Gordon College Prof. Brinton

14

Binary Trees

A binary tree T is a finite set of nodes with one of the following properties:

1. T is a tree if the set of nodes is empty. (An empty tree is a tree.)

2. The set consists of a root, R, and exactly two distinct binary trees, the left subtree TL and the right subtree TR. The nodes in T consist of node R and all the nodes in TL and TR.

Recursive

Definition

Page 15: Gordon College Prof. Brinton

15

Binary TreesA

HG

E

DB

Left Subtree

Right Subtree

Page 16: Gordon College Prof. Brinton

16

Binary TreesA

ED

CB

GF

JIH

Complete Tree (Depth 3)

A

ED

CB

GF

Complete Tree (Depth 2)Full with all possible nodes

A

ED

CB

IH

Non-Complete Tree (Depth 3)Level 2 is missing nodes

A

ED

CB

GF

KIH

Non-CompleteTree (Depth 3)Nodes at level 3 do not occupy leftmost positions

Page 17: Gordon College Prof. Brinton

17

Tree DensityA

ED

CB

GF

JIH

Total nodes (for top levels)2d - 1 23-1 = 7

Additional Nodes3

If totally complete tree: 2d - 1 + 2d

A

ED

CB

GF

A

D

CB

complete tree: 2d - 1 + 1 = 2d

Page 18: Gordon College Prof. Brinton

18

Tree Density

If totally complete tree: 2d - 1 + 2d

A

ED

CB

GF

A

D

CB

complete tree: 2d - 1 + 1 = 2d

2d <= n <= 2d+1 - 1 < 2d+1

N nodes of complete tree satisfy inequality

d <= log2 n < d+1

Height (depth) of n node tree: int (log2 n)

Page 19: Gordon College Prof. Brinton

19

Array Representation of Binary Trees

• Store the ith node in the ith location of the array

Page 20: Gordon College Prof. Brinton

20

Array Representation of Binary Trees

• Works OK for complete trees, not for sparse trees

Page 21: Gordon College Prof. Brinton

21

Linked Representation of Binary Trees

• Pros:– Uses space more efficiently– Provides additional flexibility

• Con: more overhead• Each node has two links

– one to the left child of the node– one to the right child of the node– if no child node exists for a node, the link is set to

NULL

Page 22: Gordon College Prof. Brinton

22

Linked Representation of Binary Trees

• Example

Page 23: Gordon College Prof. Brinton

23

Binary Trees as Recursive Data Structures

• A binary tree is either empty … or• Consists of

– a node called the root– root has pointers to two

disjoint binary (sub)trees called …• right (sub)tree• left (sub)tree

Anchor

Inductive step

Which is either empty … or …

Which is either empty … or …

Page 24: Gordon College Prof. Brinton

24

Tree Traversal is Recursive

If the binary tree is empty thendo nothing

Else N: Visit the root, process dataL: Traverse the left subtreeR: Traverse the right subtree

The "anchor"

The inductive step

Page 25: Gordon College Prof. Brinton

25

Traversal OrderThree possibilities for inductive step:• Left subtree, Node, Right subtree

the inorder traversal

• Node, Left subtree, Right subtreethe preorder traversal

• Left subtree, Right subtree, Nodethe postorder traversal

Page 26: Gordon College Prof. Brinton

26

Traversal Order• Given expression

A – B * C + D• Represent each operand as

– The child of a parent node

• Parent node,representing the corresponding operator

Page 27: Gordon College Prof. Brinton

27

Traversal Order

• Inorder traversal produces infix expression A – B * C + D

• Preorder traversal produces the prefix expression + - A * B C D

• Postorder traversal produces the postfix or RPN expression A B C * - D +

Page 28: Gordon College Prof. Brinton

28

Traversal Order

• Iterative Level-Order Scan

Visit +Visit - DVisit A *Visit B C

How is this possible?

Page 29: Gordon College Prof. Brinton

29

Traversal Order

• Iterative Level-Order Scan

Visit +Visit - DVisit A *Visit B C

How is this possible?

Use a queue as the intermediate storage device

Page 30: Gordon College Prof. Brinton

30

Traversal Order

• Iterative Level-Order Scan

Visit +Visit - DVisit A *Visit B C

Initialization Step: node<T> *root;queue<node<T> *> q;q.push(root);

Iterative Step: 1. Get node N pointer from Q (if Q empty exit)2. Delete a node N pointer from Q 3. Visit the node N4. Push node N’s children onto Q5. Go to step 1

Page 31: Gordon College Prof. Brinton

31

Binary Search Tree (BST)• Collection of Data Elements

– binary tree– each node x,

• value in left child of x value in x in right child of x

• Basic operations– Construct an empty BST– Determine if BST is empty– Search BST for given item

≤ ≤

Page 32: Gordon College Prof. Brinton

32

Binary Search Tree (BST)

• Basic operations (continued)– Insert a new item in the BST

•Maintain the BST property– Delete an item from the BST

•Maintain the BST property– Traverse the BST

•Visit each node exactly once•The inorder traversal must visit the values in the nodes in ascending order

Page 33: Gordon College Prof. Brinton

33

template <class elemType>class BST{private: template<class T>struct nodeType{ T info; nodeType<T> *llink; nodeType<T> *rlink;};

public: bool isEmpty(); void inorderTraversal(); void preorderTraversal(); ... binaryTreeType(const binaryTreeType<elemType>& otherTree); binaryTreeType(); ~binaryTreeType();

Page 34: Gordon College Prof. Brinton

34

private:

nodeType<elemType> *root;

void copyTree(nodeType<elemType>* &copiedTreeRoot, nodeType<elemType>* otherTreeRoot); ... void destroy(nodeType<elemType>* &p); void inorder(nodeType<elemType> *p); void preorder(nodeType<elemType> *p);

};

Page 35: Gordon College Prof. Brinton

35

BST TraversalsPublic method

void inorderTraversal();

Private recursive auxillary method

template<class elemType>void binaryTreeType<elemType>::inorder(nodeType<elemType> *p){

if(p != NULL){

inorder(p->llink);cout<<p->info<<" ";inorder(p->rlink);

}}

Page 36: Gordon College Prof. Brinton

36

BST Leaf CountCreate a method that returns leaf count…

Page 37: Gordon College Prof. Brinton

37

BST Leaf Countint binaryTreeType<elemType>::treeLeavesCount(){return leavesCount(root);}

template<class elemType>int binaryTreeType<elemType>::leavesCount(nodeType<elemType> *p){

if (p != NULL) {

if (p->llink == NULL && p->rlink == NULL)return 1;

elsereturn (leavesCount(p->llink) + leavesCount(p->rlink));

} elsereturn 0;

}

Page 38: Gordon College Prof. Brinton

38

BST Searches

• Search begins at root– If that is desired item, done

• If item is less, move downleft subtree

• If item searched for is greater, move down right subtree

• If item is not found, we will run into an empty subtree

Page 39: Gordon College Prof. Brinton

39

BST Searches

• Search begins at root– If that is desired item, done

• If item is less, move downleft subtree

• If item searched for is greater, move down right subtree

• If item is not found, we will run into an empty subtree

2d <= n <= 2d+1 - 1 < 2d+1

Remember: N nodes of complete tree satisfy inequality

d <= log2 n < d+1 d is levels

Height of n node tree: int (log2 n)

Max compares for complete tree: (int) log2 n + 1

Page 40: Gordon College Prof. Brinton

40

Iterative Inserting into a BST

• Insert function – Letter R– Uses modified version of search

to locate insertion location or already existing item

– Pointer parent trails search pointer locptr, keeps track of parent node

– Thus new node can be attached to BST in proper place

R

Page 41: Gordon College Prof. Brinton

41

(Recursive) Inserting into a BST• Insert function

– Base case• Root pointer = null (empty)

– Create new node and return pointer to this new tree

– Recursive case• If root pointer != null (not empty)

– Compare new item to root’s item– If item > root item then insert into

right subtree (insert root->rllink)– If item < root item then insert into

left subtree– If item = root item then don’t insert

30

10

7015

Page 42: Gordon College Prof. Brinton

42

(Recursive) Inserting into a BST

30

10

7015

Page 43: Gordon College Prof. Brinton

43

Recursive Deletion

Three possible cases to delete a node, x, from a BST

1. The node, x, is a leaf

Page 44: Gordon College Prof. Brinton

44

Recursive Deletion

2. The node, x has one child

Page 45: Gordon College Prof. Brinton

45

Recursive Deletion

• x has two children

Replace contents of x with inorder successor

K

Delete node pointed to by xSucc as described for

cases 1 and 2

Page 46: Gordon College Prof. Brinton

46

Problem of Lopsidedness

• Tree can be balanced– each node except leaves has exactly 2 child

nodes

Page 47: Gordon College Prof. Brinton

47

Problem of Lopsidedness

• Trees can be unbalanced– not all nodes have exactly 2 child nodes

Page 48: Gordon College Prof. Brinton

48

Problem of Lopsidedness

• Trees can be totally lopsided– Suppose each node has a right child only– Degenerates into a linked list

Processing time affected by

"shape" of tree

Page 49: Gordon College Prof. Brinton

49

Threaded Binary Search Trees

• Use special links in a BST– These threads provide efficient nonrecursive

traversal algorithms– Build a run-time stack into the tree for recursive

calls

Page 50: Gordon College Prof. Brinton

50

Threaded Binary Search Trees• Note the sequence

of nodes visited– Left to right

• A right threaded BST– Whenever a node, x, with null right pointer is

encountered, replace right link with thread to inorder successor of x

– Inorder successor of x is its parent if x is a left child– Otherwise it is nearest ancestor of x that contains x in its

left subtree

Page 51: Gordon College Prof. Brinton

51

Threaded Binary Search TreesTraversal algorithm 1. Initialize a pointer, ptr, to the root of tree2. While ptr != null

a. While ptr->left not nullreplace ptr by ptr->left

b. Visit node pointed to by ptrc. While ptr->right is a thread do following

i. Replace ptr by ptr->rightii. Visit node pointed to by ptr

d. Replace ptr by ptr->rightEnd while

Page 52: Gordon College Prof. Brinton

52

Threaded Binary Search Treespublic: DataType data; bool rightThread; BinNode * left; BinNode * right; // BinNode constructors // Default -- data part is default DataType value // -- right thread is false; both links are null BinNode() : rightThread(false, left(0), right(0) { }

//Explicit Value -- data part contains item; rightThread // -- is false; both links are null BinNode (DataType item) : data(item), rightThread(false), left(0), right(0) { }}; // end of class BinNode declared

Additional field, rightThread

required


Recommended