59
1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

Embed Size (px)

Citation preview

Page 1: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

1

Binary TreesBinary Trees Binary Search TreesBinary Search Trees

CSE 30331Lecture 13 –Trees

Page 2: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

2

Reading

Binary Trees Ford: Ch 10

Page 3: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

3

Tree Structures

President-CEO

ProductionManager

SalesManager

ShippingSupervisor

PersonnelManager

WarehouseSupervisor

PurchasingSupervisor

HIERARCHICAL TREE STRUCTURE

Page 4: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

4

Tree Structures

+

e

/

ba

*

dc

-

B IN ARY EXPRES S IO N T REE FO R " a* b + (c -d ) / e "

Page 5: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

5

Tree Structures

A

JI

HGFE

DCB

(a)

(b )

A G EN ERAL T REE

Page 6: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

6

Tree Terminology Node – location containing value(s) Parent – node 1 link above “here” in tree Child – node 1 link below “here” in tree Root – top (first) node in tree Leaf – A node without any children Interior node – any non-leaf node Ancestor – any node on a path between root and “here” Descendent – any node reachable by a path from “here”

downward in tree Level – number of links traversed from root to “here” Height (depth) – length of longest path from root to any leaf Subtree – Any node (chosen as root) along with all of its

descendents

Page 7: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

7

Tree Node Level and Path Length

A

HG

FE

DCB

L e ve l: 0

L e ve l: 1

L e ve l: 2

L e ve l: 3

Page 8: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

8

Binary Tree Definition

A binary tree T is a finite set of nodes with one of the following properties: (a) T has no nodes (it is the empty tree). (b) The set consists of …

a root R a left subtree TL

a right subtreeTR.

Page 9: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

9

Samples of Binary Trees

A

E

D

C

B

A

F

H

ED

CB

I

T ree ASiz e 9 D ep t h 3

T ree BSiz e 5 D ep t h 4

G

Page 10: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

10

Tree Node Level and Path Length – Depth Discussion

A

ED

CB

GF

JIH

C o m p let e T ree (D ep t h 3 )

Page 11: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

11

Tree Node Level and Path Length – Depth Discussion

A

ED

CB

GF

Complete Tree (Depth 2)Also a full binary tree.

Contains maximum number of leaves

Page 12: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

12

Tree Node Level and Path Length – Depth Discussion

A

ED

CB

IH

N o n -C o m p let e T ree (D ep t h 3 )Lev el 2 is m is s in g n o d es

Page 13: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

13

Tree Node Level and Path Length – Depth Discussion

A

ED

CB

GF

KIH

N o n -C o m p let eT ree (D ep t h 3 )N o d es at lev el 3 d o n o t o ccu rp y left m o s t p o s it io n s

Page 14: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

14

Binary Tree Nodes

Abs tract T re e M ode l

A

E F

H

D

CB

G

l e ft A ri gh t

T re e N ode M ode l

l e ft B ri gh t

l e ft E ri gh t

l e ft G ri gh t

l e ft D ri gh t

l e ft C ri gh t

l e ft H ri gh t

l e ft F ri gh t

Page 15: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

15

Tree Node Classtemplate <typename T>class tnode{ public:

// public data simplifies building class functions T nodeValue; tnode<T> *left, *right;

// default constructor. data not initialized tnode() {}

// initialize the data members tnode (const T& item, tnode<T> *lptr = NULL, tnode<T> *rptr = NULL) : nodeValue(item), left(lptr), right(rptr) {}};

Page 16: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

16

Tree Traversals

A

F

H

ED

CB

I

Tree ASize 9 Depth 3

G

Inorder: D B H E I A F C G

Postorder: D H I E B F G C A

Preoder: A B D E H I C F G

Level-Order: A B C D E F G H I

Page 17: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

17

Inorder Traversal

Algorithm (1) traverse left subtree (2) process root (3) traverse right subtree

// version to output values in tree “inorder”

template <typename T>void inorderOutput(tnode<T> *t, const string& separator = " "){ if (t != NULL) { inorderOutput(t->left, separator); // descend left cout << t->nodeValue << separator; // output the node inorderOutput(t->right, separator); // descend right }}

Page 18: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

18

Postorder TraversalAlgorithm (1) traverse left subtree (2) traverse right subtree (3) process root

// version to output values in tree “postorder”

template <typename T>void postorderOutput(tnode<T> *t, const string& separator = " "){ if (t != NULL) { postorderOutput(t->left, separator); // descend left postorderOutput(t->right, separator); // descend right cout << t->nodeValue << separator; // output the node }}

Page 19: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

19

Preorder TraversalAlgorithm (1) process root (2) traverse left subtree (3) traverse right subtree

// version to output values in tree “preorder”

template <typename T>void preorderOutput(tnode<T> *t, const string& separator = " "){ if (t != NULL) { cout << t->nodeValue << separator; // output the node postorderOutput(t->left, separator); // descend left postorderOutput(t->right, separator); // descend right }}

Page 20: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

20

Level-order traversal

Similar to breadth-first search

Traverses each level of the tree, in turn, from left to right

AlgorithmPush root on queueWhile queue not empty

pop node from queueprocess nodepush left and right child of node onto queue

Page 21: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

21

Level-order Traversaltemplate <typename T>void levelorderOutput(tnode<T> *t, const string& separator = " "){ // store siblings of each node in a queue so that they are // after parent, and in order for next level of tree queue<tnode<T> *> q; tnode<T> *p;

q.push(t); // start by pushing root (t) onto queue while(!q.empty()) { p = q.front(); // process front queue node q.pop(); cout << p->nodeValue << separator; if(p->left != NULL) q.push(p->left); // push left child in queue if(p->right != NULL) q.push(p->right); // push right child on queue }}

Page 22: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

22

Node Density

Full Tree (to depth k, or level k)

2k+1 -1 nodes

2k - 1 interior nodes

2k leaves

Complete Tree with n nodes

depth is log2n

Node count inequality 2k <= n < 2k+1

leads to k <= log2n < k+1

Page 23: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

23

Counting Leaves

Algorithm (different from text)if tree is empty

return 0else if root has no children

return 1else

return leaves(TL) + leaves(TR)

Page 24: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

24

Counting Leaves

template <typename T>int countLeaf (tnode<T> *t){ if (t == NULL) return 0; else if (t != NULL) { // if t is a leaf node (no children), it counts. if (t->left == NULL && t->right == NULL) return 1;

return (countLeaf(t->left + countLeaf(t->right); }}

Page 25: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

25

Tree Depth (Height)

Tree height is 1 + MAX(depth(TL),depth(TR))

Algorithm

If tree is empty

return -1

else

return 1 + MAX(depth(TL),depth(TR))

Page 26: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

26

Depth (Height)int depth (tnode<T> *t){ int depthLeft, depthRight, depthval;

if (t == NULL) depthval = -1; // depth of an empty tree is -1 else

{ depthLeft = depth(t->left); depthRight = depth(t->right); // depth is 1 + maximum subtree depth

depthval = 1 + (depthLeft > depthRight ? depthLeft : depthRight); }

return depthval;}

Page 27: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

27

Deleting a treeAlgorithm

if tree not emptydelete both subtreesdelete root

template <typename T>void deleteTree(tnode<T> *t){ // postorder delete left and right subtrees of t // and then delete node t if (t != NULL) { deleteTree(t->left); deleteTree(t->right); delete t; }}

Page 28: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

28

Binary Search Tree Definition

A binary search tree T is

(a) a binary tree, and

(b) each and every internal node R and its children (CL and CR), if they exist, have values such that (valueCL

< valueR <= valueCR)

Page 29: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

29

Binary Search Trees

6 53 0

3 71 0

2 5

1 5

B in ary Search T ree 1

B in ary Search T ree 2

5 3

3 0

5 9

6 2

5 0

B in ary Search T ree 3

Page 30: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

30

CLASS stree Constructors “d_stree.h”

stree();Create an empty search tree.

stree(T *first, T *last);Create a search tree with the elements from the

pointer range [first, last).

CLASS stree Opertions “d_stree.h”

void displayTree(int maxCharacters);Display the search tree. The maximum number of

characters needed to output a node value is maxCharacters.bool empty();

Return true if the tree is empty and false otherwise.

Page 31: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

31

CLASS stree Opertions “d_stree.h”

int erase(const T& item);Search the tree and remove item, if it is present;

otherwise, take no action. Return the number of elements removed.

Postcondition: If item is located in the tree, the size of the tree decreases by 1.

void erase(iterator pos);Erase the item pointed to the iterator pos.

Precondition: The tree is not empty and pos points to an item in the tree. If the iterator is invalid, thefunction throws the referenceError exception.

Postcondition: The tree size decreases by 1.

Page 32: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

32

CLASS stree Opertions “d_stree.h”

void erase(iterator first, iterator last);Remove all items in the iterator range [first, last).

Precondition: The tree is not empty. If empty, the function throws the underflowError exception.

Postcondition: The size of the tree decreases by the number of items in the range.

iterator find(const T& item);Search the tree by comparing item with the data

values in a path of nodes from the root of the tree. If a match occurs, return an iterator pointing to the matching value in the tree. If item is not in the tree, return the iterator value end().

Page 33: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

33

CLASS stree Opertions “d_stree.h”

pair<iterator, bool> insert(const T& item);If item is not in the tree, insert it and return an iterator-bool pair where the iterator is the location of the new

element and the Boolean value is true. If item is already in the tree, return the pair where the iterator locates the existing item and the Boolean value is false.

Postcondition: The size of the tree is increased by 1 if item is not present in the tree.

int size();Return the number of elements in the tree.

Page 34: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

34

What is a pair? Examples later.

The pair template data type is defined in the <utility> header file

It has two public members first and second The insert(item) function returns a pair containing an

iterator and a bool first is the iterator and it indicates the node in the Stree

containing the item second is a bool indicating whether the node was actually

added to the tree (true) or was already there (false) So, the pair gives a function a way to return two

values instead of one

Page 35: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

35

STree Node Classtemplate <typename T>class stnode{ public: // public data simplifies building class functions T nodeValue; stnode<T> *left, *right, *parent;

// default constructor. data not initialized tnode() {}

// initialize the data members stnode (const T& item, stnode<T> *lptr = NULL, stnode<T> *rptr = NULL, stnode<T> *pptr = NULL) : nodeValue(item), left(lptr), right(rptr), parent(pptr)

{}};

Page 36: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

36

Stree Iterators Perform INORDER traversals of tree Iterator and const_iterator are implemented as contained classes

within Stree class See “d_stree.h” and d_siter.h” Iterator is a two part object with pointer to root of Stree and to

current Stnode (see below)

private: stnode<T> *nodePtr; // current location in tree stree<T> *tree; // the tree

// used to construct an iterator return value // from an stnode pointer iterator (stnode<T> *p, stree<T> *t) : nodePtr(p), tree(t) {}

Page 37: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

37

Locating value 37 in a BSTCurrent Node ActionRoot = 50 Compare item = 37 and 50 37 < 50, move to the left subtreeNode = 30 Compare item = 37 and 30 37 > 30, move to the right subtreeNode = 35 Compare item = 37 and 35 37 > 35, move to the right subtreeNode = 37 Compare item = 37 and 37. Item found.

50

62373210

60533525

5530

15

Page 38: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

38

FindNode() function

template <typename T>stnode<T> *stree<T>::findNode(const T& item) const{

// cycle t through the tree starting with rootstnode<T> *t = root;// terminate on on empty subtreewhile(t != NULL && (item != t->nodeValue))

if (item < t->nodeValue)t = t->left;

else t = t->right;

// return pointer to node; NULL if not foundreturn t;

}

Page 39: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

39

Stree find() function

template <typename T>stree<T>::iterator stree<T>::find(const T& item){

stnode<T> *curr;// search tree for itemcurr = findNode (item);// if item found, return iterator with value curr;// otherwise, return end()if (curr != NULL)

return iterator(curr, this);else

return end();}

Page 40: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

40

Inserting into search tree All insertions are as LEAVES

Algorithm if tree is empty insert new node here

else if new value == node value return without inserting

else if new value < node value insert in left subtree

else if new value > node value insert in right subtree

Page 41: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

41

Insert() functiontemplate <typename T>pair<stree<T>::iterator, bool> stree<T>::insert(const T& item){ stnode<T> *t = root, *parent = NULL, *newNode; while(t != NULL) { parent = t; if (item == t->nodeValue) // found a match return pair<iterator, bool> (iterator(t,this),false); else if (item < t->nodeValue) t = t->left; else t = t->right; }

newNode = getSTNode(item,NULL,NULL,parent);if (parent == NULL) // insert as root node

root = newNode;else if (item < parent->nodeValue) // insert as left child

parent->left = newNode; else // insert as right child

parent->right = newNode;treeSize++; return pair<iterator, bool> (iterator(newNode, this), true);

}

Page 42: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

42

Insertion: 1st of 3 steps

The function begins at the root node and compares item 32 with the root value 25. Since 32 > 25, we traverse the right subtree and look at node 35.

2 5

4 01 2

3 52 0

p aren t

t

(a)St ep 1 : C o m p are 3 2 an d 2 5 .T rav ers e t h e righ t s u b t ree.

Page 43: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

43

Insertion: 2nd of 3 steps

Considering 35 to be the root of its own subtree, we compare item 32 with 35 and traverse the left subtree of 35.

(b )St ep 2 : C o m p are 3 2 an d 3 5 .T rav ers e t h e left s u b t ree.

2 5

4 01 2

3 52 0

t

p aren t

Page 44: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

44

Insertion: 3rd of 3 steps

Create a leaf node with data value 32, and insert the new node as the left child of node 35. newNode = getSTNode(item,NULL,NULL,parent);

parent->left = newNode;

(c)St ep 3 : In s ert 3 2 as left ch ildo f p aren t 3 5

2 5

4 01 2

3 52 0 p aren t

3 2

Page 45: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

45

Deleting a node

Three cases (1) node that is a leaf

Just delete it

(2) node with single child Delete node and replace it in tree with its child

(3) node with two children Find inorder successor

This will be a leaf or a node with only a Right child Swap value of node and its inorder successor Delete successor node (now case 1 or 2)

Page 46: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

46

Erase() functiontemplate <typename T>void stree<T>::erase(iterator pos){ // dNodePtr = pointer to node D that is deleted // pNodePtr = pointer to parent P of node D // rNodePtr = pointer to node R that replaces D stnode<T> *dNodePtr = pos.nodePtr, *pNodePtr, *rNodePtr;

if (treeSize == 0) throw underflowError("stree erase(): tree is empty");

if (dNodePtr == NULL) throw referenceError("stree erase(): invalid iterator");

// assign pNodePtr the address of P pNodePtr = dNodePtr->parent;

// now determine which case deletion we have // leaf node or node with single child (easy cases) // or node with 2 children (hard case) // continued ....

Page 47: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

47

Erase() // If D has a NULL pointer, the // replacement node is the other child if (dNodePtr->left == NULL || dNodePtr->right == NULL) { if (dNodePtr->right == NULL) rNodePtr = dNodePtr->left; // replacement: left child else rNodePtr = dNodePtr->right; // replacement: right child

if (rNodePtr != NULL) // the parent of R is now the parent of D rNodePtr->parent = pNodePtr; } else // node has two children { // find inorder successor, right & then all the way left stnode<T> *pOfRNodePtr = dNodePtr; // parent of successor rNodePtr = dNodePtr->right; // step right while(rNodePtr->left != NULL) { pOfRNodePtr = rNodePtr; rNodePtr = rNodePtr->left; // step left ... }

Page 48: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

48

Erase() if (pOfRNodePtr == dNodePtr) { // right child of deleted node is the replacement. rNodePtr->left = dNodePtr->left; rNodePtr->parent = pNodePtr; dNodePtr->left->parent = rNodePtr; } else { // we moved at least one node down a left branch // of the right child of D. link right subtree of R // as left subtree of parent of R pOfRNodePtr->left = rNodePtr->right; if (rNodePtr->right != NULL) rNodePtr->right->parent = pOfRNodePtr;

// link R to D’s children and parent rNodePtr->left = dNodePtr->left; rNodePtr->right = dNodePtr->right; rNodePtr->parent = pNodePtr; rNodePtr->left->parent = rNodePtr; rNodePtr->right->parent = rNodePtr; } }

Page 49: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

49

Erase() // finally, connect R as correct child of parent node of D

// if deleting the root node. assign new root if (pNodePtr == NULL) root = rNodePtr; // else attach R as correct child of P else if (dNodePtr->nodeValue < pNodePtr->nodeValue) pNodePtr->left = rNodePtr; else pNodePtr->right = rNodePtr;

// delete the node from memory and decrement tree size delete dNodePtr; treeSize--;}

Page 50: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

50

Removing an Item From a Binary Tree

1 0D

P

D e le te le a f n o d e 1 0 .p N o d e P tr-> le ft is d N o d e

N o re p la c e m e n t is n e c e s s a ry.p N o d e P tr-> le ft is N U L L

B efo re A ft er

4 0

3 5

6 53 0

5 0

3 32 6

2 5

3 42 9

2 8

P

4 0

3 5

6 53 0

5 0

3 32 6

2 5

3 42 9

2 8

Page 51: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

51

Removing an Item From a Binary Tree

D

P

D e le te n o de 3 5 with o n ly a le f t ch ild: No de R is th e le f t ch ild.

B e fo re

R

40

35

6530

50

3310 26

25

3429

28

P

A tta ch n o de R to th e pa re n t .

A fte r

R

40

33

6530

50

10 26

25

34

29

28

Page 52: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

52

Removing an Item From a Binary Tree

P

D e le te n o d e 2 6 w ith o n ly a rig h t c h ild : N o d e R is th e rig h t c h ild .

P

A tta c h n o d e R to th e p a re n t.

B efo re A ft er

R

R

4 0

3 5

6 53 0

5 0

3 31 0 2 6

2 5

3 42 9

2 8

4 0

3 5

6 53 0

5 0

3 31 0 2 9

2 5

3 42 8

D

Page 53: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

53

Removing an Item From a Binary Tree

4 0

3 5

6 53 0

D e le te n o d e 3 0 w ith tw o c h ild re n .

5 0

3 31 0 2 6

2 5

3 42 9

2 8

4 0

3 5

6 5

O rp h a n e d s u b tre e s .

5 0

3 31 0

2 5

3 4

2 6

2 9

2 8

Page 54: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

54

Removing an Item From a Binary Tree

D

R

d N o d eP t r

rN o d eP t rp O fR N o d eP t r

Pp N o d eP t r 4 0

3 5

6 53 0

5 0

3 31 0 2 6

2 5

3 42 9

2 8

P

R

4 0

3 5

6 53 0

5 0

3 41 0

2 6

3 3

2 9

2 8

p N o d eP t r

DR

rN o d eP t r

p O fR N o d eP t r

B efo re u n lin k in g R A ft er u n lin k in g R

Page 55: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

55

Removing an Item From a Binary Tree

P

4 0

3 5

6 53 3

5 0

3 41 0

2 6

2 9

2 8

p N o d eP t r

RrN o d eP t r

P

4 0

3 5

6 53 0

5 0

3 41 0

2 6

2 9

2 8

p N o d eP t r

D3 3R

rN o d eP t r

B efo re rep lacin g D b y R A ft er rep lacin g D b y R

Page 56: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

56

Simple Application -- Removing Duplicates Since a binary search tree does not insert

duplicates, a vector can be purged of duplicates by …

For each element in vector Insert element in binary search tree

Clear vector For each element in binary search tree

Append element to vector Clear binary search tree If the search tree is traversed “inorder” this results in

a sort of the vector as well

Page 57: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

57

Using Binary Search Trees Application: Removing Duplicates

7

52

37 3 2 5 3 2 9 3 2 3 5 7 9

9v v

Page 58: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

58

Stree begin() and end()template <typename T>stree<T>::iterator stree<T>::begin(){ stnode<T> *curr = root; // if the tree is not empty, the first node // inorder is the farthest node left from root if (curr != NULL) while (curr->left != NULL) curr = curr->left;

// build return value using private constructorreturn iterator(curr, this);

}

template <typename T>stree<T>::iterator stree<T>::end(){

// end indicated by iterator with NULL stnode pointerreturn iterator(NULL, this);

}

Page 59: 1 Binary Trees Binary Trees Binary Search Trees Binary Search Trees CSE 30331 Lecture 13 –Trees

59

Stree iterator preincrement operator++iterator& operator++ () // preincrement. move forward inorder{ stnode<T> *p; if (nodePtr == NULL) // ++ from end() { nodePtr = tree->root; // start at root if (nodePtr == NULL) throw underflowError("stree iter op++ (): t empty"); // move to smallest value in tree, 1st node inorder while (nodePtr->left != NULL) nodePtr = nodePtr->left; } else if (nodePtr->right != NULL) { // find successor { nodePtr = nodePtr->right; // step right while (nodePtr->left != NULL) nodePtr = nodePtr->left; // go all the way left } else // move up the tree, looking for a parent having { // *nodePtr is left child p = nodePtr->parent; while (p != NULL && nodePtr == p->right) { nodePtr = p; p = p->parent; } nodePtr = p; // now, either p is NULL or *p is the successor } return *this;}