Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by...

33
Binary Trees Chapter 10

Transcript of Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by...

Page 1: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Binary Trees

Chapter 10

Page 2: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Introduction

• Previous chapter considered linked lists– nodes connected by two or more links

• We seek to organize data in a linked structure such that– it can be searched more efficiently– it can be used in new ways

• We begin with a review of search algorithms

Page 3: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Linear Search

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

– 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

Page 4: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

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++; }}

Page 5: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

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 ==) return; if (item == locptr->data) found = true; else loc++; }}

In both cases, the worst case computing

time is still O(n)

In both cases, the worst case computing

time is still O(n)

Page 6: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

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; }

}

Page 7: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Binary Search

• Usually outperforms a linear search

• Disadvantage:– Requires a sequential storage– Not appropriate for linked lists (Why?)

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

Page 8: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Binary Search Tree

• Consider the following ordered list of integers

1. Examine middle element

2. Examine left, right sublist (maintain pointers)

3. (Recursively) examine left, right sublists

80666249352813

Page 9: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Binary Search Tree

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

80

66

62

49

35

28

13

Page 10: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

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 11: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Trees

80

66

62

49

35

28

13 70

Root node

• Children of the parent (66)

• Siblings to each other

Leaf nodes

Page 12: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

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

• Example– multiple coin tosses– encoding/decoding messages in dots and

dashes such as Mores code

Page 13: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Array Representation of Binary Trees

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

• Works OK for complete trees, not for sparse trees

U

T

P

O

E

M

C

0

1 2

3 4 5 6

Page 14: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Linked Representation of Binary Trees

• Uses space more efficiently

• Provides additional flexibility

• 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

data

left right

left child

right child

Page 15: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

ADT 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 16: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

ADT Binary Search Tree (BST)

• Basic operations (ctd)– 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 17: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

BST Class Template

template <typename t>class BST{ private: /* Node structure */

class BinNode{ public:

t data;BinNode *left, *right;BinNode() { left = right = 0; }BinNode (t item) { data = item; left = right = 0; }

}; // end of class BinNode// ctd ->

Page 18: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

BST Class Template

. . .

typedef BinNode *BinNodePointer;

public: // for BST

BST(); // construct an empty BST

bool Empty() const;

private:

BinNodePointer root;

}; // end of class template declaration

Page 19: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

BST Class Template

• Definition of constructortemplate <typename t>BST <t>::BST()

{ root = 0; }

• Definition of Empty()template <typename t>

bool BST<t>::Empty(){ return root == 0; }

Page 20: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Searching a BST

template <typename t>bool BST <t>::Search(const t &item) const{ BinNodePointer locptr = root;

bool found = false;for ( ; ; ){ if found || locptr == 0) break; if (item < locptr->data) locptr = locptr->left; // descend left

else if (item > locptr->data) locptr = locptr->right; // descend right

else found = true;}

return found;}

Reached a leaf node without finding a match

Reached a leaf node without finding a match

Page 21: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Inserting an Item into a BST

template <typename t>

void BST<t>::Insert (const t &item)

{ BinNodePointer locptr = root; parent =0;bool found = false;for ( ; ; )

{ if found || locptr == 0) break; if (item < locptr->data) locptr = locptr->left; // descend left

else if (item > locptr->data) locptr = locptr->right; // descend right

else found = true;}if (found) cerr << "Item already in the tree\n"; . . .

Page 22: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Inserting an Item into a BST

else

{ locptr = new BinNode (item); // construct node containing item

if (parent == 0) // empty tree root = locptr; else if (item < parent->data) // insert left of parent parent->left = locptr else // insert right of parent parent->right = locptr;

} // end of the else

} end of the Insert

Page 23: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Problem of Lopsidedness

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

nodes

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

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

Page 24: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Problem of Lopsidedness

• Balanced tree search has O(log2n)– best case

• Tree degenerated into linked list has search O(n)– worst case

• Other unbalanced trees somewhere in between• In general

– Not possible to predict how to insert to create balanced tree

– May require rebalancing algorithm

Page 25: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

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

AnchorAnchor

Inductive step

Inductive step

Which is either empty … or …

Which is either empty … or …

Which is either empty … or …

Which is either empty … or …

Page 26: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Tree Traversal is Recursive

If the binary tree is empty thendo nothing

Else L: Traverse the left subtreeN: Visit the rootR: Traverse the right subtree

The "anchor"

The inductive step

Page 27: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Traversal Order

Three 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 28: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Traversal Order• Given expression

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

– the child of a parent node– representing the corresponding operator

+

- D

A *

B C

Page 29: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

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 30: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Traversing a Binary Tree

template <typename t>void BST<t>::Inorder(ostream &out){ InorderAux (out, root); }

template <typename t>void BST<t>::InorderAux (ostream& out,

BinNodePointer ptr){ if (ptr != 0)

{ InorderAux (opt, ptr->left); out << ptr-> data << " "; InorderAux(out, ptr->right);}

}

Two functions needed:

• We can send a message to a BST object … but …

• Cannot send a message to its root, required by recursion

•Inorder sends message to the root

Two functions needed:

• We can send a message to a BST object … but …

• Cannot send a message to its root, required by recursion

•Inorder sends message to the root

Change order of these three statements for different traversals

Change order of these three statements for different traversals

Page 31: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Recursive Searching

template <typename t>bool BST<t>::Search (const t &item){ SearchAux (root, item); }

template <typename t>void BST<t>::SearchAux (BinNodePointer locptr,

const t &item){ if (locptr == 0) return false; // empty tree if (item < locptr->data)

SearchAux(locptr->left, item);else if (item > locptr->data)

SearchAux (locptr->right, item);else return true;

}

Author suggests iterative approach is easier, just as efficient

Author suggests iterative approach is easier, just as efficient

Page 32: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Recursive Insertion

template <typename t>bool BST<t>::Insert (const t &item){ InsertAux (root, item); }

template (typename t>void BST<t>::InsertAux (BinNodePointer locptr,

const t &item){ if (locptr == 0) root = new BSTNode (item); else if (item < locptr->data)

InsertAux (locptr->left, item);else if (item > locptr->data)

InsertAux (locptr->right, item);else cerr << "Item already in tree\n";

}

Page 33: Binary Trees Chapter 10. Introduction Previous chapter considered linked lists –nodes connected by two or more links We seek to organize data in a linked.

Recursive Deletion

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

• The node, x, is a leaf

• x has one child

• x has two children

• Note the source code for the deletion function, pgs 548 - 550