§3 binary tree traversals —— visit each node exactly...

26
§3 Binary Tree Traversals —— visit each node exactly once L ::= move left ; R ::= move right ; V ::= visit the node. We will always traverse the left subtree before the right one LVR LRV VLR Inorder traversal Postorder traversal Preorder traversal Example Given a syntax tree of an expression (infix) A + B C D + A D B C Then LVR A + B C D LRV A B C D + VLR + A B C D

Upload: cedric-grimes

Post on 02-Jan-2016

12 views

Category:

Documents


1 download

DESCRIPTION

+. A. . . D. B. C. §3 Binary Tree Traversals —— visit each node exactly once. L ::= move left ; R ::= move right ; V ::= visit the node. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§3 Binary Tree Traversals —— visit each node exactly once

L ::= move left ; R ::= move right ; V ::= visit the node.

We will always traverse the left subtree before the right one LVR 、 LRV 、 VLR

Inordertraversal

Postordertraversal

Preordertraversal

〖 Example 〗 Given a syntax tree of an expression (infix)

A + B C D+

A

D

B C

Then LVR A + B C D

LRV A B C D +

VLR + A B C D

Page 2: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§3 Binary Tree Traversals

Traversal

+

A

D

B C

Recursive Programvoid inorder (treePointer ptr ){ if ( ptr ) { inorder ( ptr->leftChild ); printf ( “ %d”, ptr->data ); inorder ( ptr->rightChild ); }}

Tp = O( n )

Preorder Traversal

void preorder (treePointer ptr ){ if ( ptr ) { printf ( “ %d”, ptr->data ); preorder ( ptr->leftChild ); preorder ( ptr->rightChild ); }}

Postorder Traversal

void postorder (treePointer ptr ){ if ( ptr ) { postorder ( ptr->leftChild ); postorder ( ptr->rightChild ); printf ( “ %d”, ptr->data ); }}

Inorder Traversal

Page 3: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§3 Binary Tree Traversals

Inorder Traversal

+

A

D

B C

AlgorithmStep 1 : move down along the left path untill

NULL is reached;Step 2 : visit\print the parent node;Step 3 : if ( parent has a right child ) { move to the right node; repeat steps 1 to 3; } else { move to the next higher level until the parent of the current node has been visited; repeat steps 2 to 3; }Iterative Program

void iterInorder ( treePointer node ){ int top = 1; /* initialize stack */ treePointer stack [ MAX_STACK_SIZE ]; for ( ; ; ) { for ( ; node; node = node->leftChild ) push (&top, node ) ; pop (&top, &node ); if ( !node ) break; printf ( “ %d”, node->data ); node = node->rightChild; }} Tp = O( n )

+

A

D

B C

Page 4: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§3 Binary Tree Traversals

Level Order Traversal —— output nodes in the order as they are numbered

AlgorithmStep 1 : add the root onto queue;Step 2 : delete \ print one node from

queue ;Step 3 : add the left, then the right child of

this node onto queue (if it is impossible, then simply continue);

Step 4 : Repeat steps 2 to 3 until queue is empty.

2

4 5

3

6 7

1

1

1

2 3

2

4 5

3

6 7

4

5 6 7

Page 5: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§3 Binary Tree Traversals

Programvoid levelOrder (treePointer ptr ){ /* level order tree traversal */ int front = rear = 0 ; treePointer queue [ MAX_QUEUE_SIZE ] ; if ( !ptr ) return ; /* empty tree */ addq (front,&rear,ptr ) ; /* push the root onto queue */ for ( ; ; ) { deleteq (&front,rear,&ptr) ; /* pop one node from queue */ if ( ptr ) { printf ( “ %d”, ptr->data ) ; if ( ptr->leftChild ) /* if left child is not NULL */ addq (front,&rear,ptr->leftChild ); /* then push it onto queue */ if ( ptr->rightChild ) /* if right child is not NULL */ addq (front,&rear,ptr->rightChild ); /* then push it onto queue */ } /* end if (ptr) */ else break ; /* if queue is empty, then finish */ } /* end for-loop */}

Can you eliminate it?

Page 6: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§4 Additional Binary Tree Operations

Copying Binary Trees: LRV where V ::= copy ( Program 5.6 on p.212 )

Testing for Equality of Binary Trees: VLR where V ::= test ( Program 5.7 on p.213 )

Create a binary tree

Compute the number of leafs in a binary tree

Compute the depth of a binary tree

Page 7: §3  Binary Tree Traversals                                      ——  visit each node exactly once

Create a binary tree

treePointer Create (treePointer bt){

treePointer bt;

char ch;

scanf(“%c”,&ch);

if (ch == ‘# ') bt = NULL;

else {

MALLOC(bt, sizeof(struct node), treePointer;

bt->data= ch; //create root

bt->leftChild = Create(); //create left subtree of root

bt->rightChild = Create(); //create right subtree of root

}

return bt;

}//Create

Page 8: §3  Binary Tree Traversals                                      ——  visit each node exactly once

int Leaf(treePointer bt)

{

if (bt == NULL) return 0;

else if ((bt->leftChild == NULL) && (bt->rightChild == NULL)) return 1;

else return (Leaf(bt->leftChild)+Leaf(bt->rightChild));

}

Compute the number of leafs in a binary tree

Page 9: §3  Binary Tree Traversals                                      ——  visit each node exactly once

Compute the depth of a binary tree

int Depth(treePointer bt){

int LeftDepth, RightDepth;if (bt == NULL) return 0;else {

LeftDepth = Depth(bt->leftChild);RightDepth = Depth(bt->rightChild);return (LeftDepth > RightDepth) ?

(LeftDepth + 1) : (RightDepth + 1);

}}

Page 10: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§5 Threaded Binary Trees

Here comes the typical question of mine:

Why do we need threaded binary trees?

Because I enjoy giving you headaches ... Just kidding.

Okay, think of a fullbinary tree with n nodes.

How many links are there?

2n links, if each node has only

the left and right-child links.

How many of them are NULL?

n + 1.

Can I stand that?

Of course not!You got it!

Any clue on how toimprove the situation?

We can replace the null links by “threads”which will make traversals

easier.

You are such agenius !

Oh well, I wish I’d have really done it

Then who should take the credit?

They are A. J. Perlis and C. Thornton.

Let’s look at the rules first

Page 11: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§5 Threaded Binary Trees

Rule 1: If ptr->leftChild is null, replace it with a pointer to the inorder predecessor of ptr.

Rule 2: If ptr->rightChild is null, replace it with a pointer to the inorder successor of ptr.

Rule 3: There must not be any loose threads. Therefore a threaded binary tree must have a head node of which the left child points to the first node.

Structuretypedef struct threaded_tree *threaded_ptr;typedef struct threaded_tree { short int leftThread; /* if it is TRUE, then left_child */ threadPointer leftChild; /* is a thread, not a child ptr. */ char data; short int rightThread; /* if it is TRUE, then right_child */ threadPointer rightChild; /* is a thread, not a child ptr. */}

Page 12: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§5 Threaded Binary Trees

+

A

D

B C

〖 Example 〗 Given the syntax tree of an expression (infix)

A + B C D

F F

F + F

T A T F F

F F T D T

T B T T C T

head node

Page 13: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§6 Heaps

Priority Queues —— delete the element with the highest \ lowest priority

How can we can use efficient data structure to represent the priority queue?

Which is the best choice?

Page 14: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§6 HeapsOptions of priority queue representation: Array :

Insertion — add one item at the end ~ ( 1 )Deletion — find the largest \ smallest key ~ ( n ) remove the item and shift array ~ O( n )

Linked List :

Insertion — add to the front of the chain ~ ( 1 )Deletion — find the largest \ smallest key ~ ( n ) remove the item ~ ( 1 )

Ordered Array :

Insertion — find the proper position ~ O( n ) shift array and add the item ~ O( n )Deletion — remove the first \ last item ~ ( 1 )

Ordered Linked List :

Insertion — find the proper position ~ O( n ) add the item ~ ( 1 )Deletion — remove the first \ last item ~ ( 1 )

Page 15: §3  Binary Tree Traversals                                      ——  visit each node exactly once

1. The Heap ADT

【 Definition 】 A max tree is a tree in which the key value in each node is no smaller than the key values in its children (if any). A max heap is a complete binary tree that is also a max tree.

【 Definition 】 A min tree is a tree in which the key value in each node is no larger than the key values in its children (if any). A min heap is a complete binary tree that is also a min tree.

9

6

5

3

[1]

[2] [3]

[4]

A max heap

10

20

50

83

[1]

[2] [3]

[4]

A min heap

The largest key The smallest key

Page 16: §3  Binary Tree Traversals                                      ——  visit each node exactly once

§6 Heaps

structure MaxHeap is

objects: A complete binary tree of n > 0 elements organized so that the values in each node is at least as large as those in its children

functions: for all heap MaxHeap, item Element, and n, max_size integer

MaxHeap Create ( max_size ) ::= creates an empty heap that can hold a maximum

of max_size elements. Boolean HeapFull ( heap, n ) ::= if ( n = = max_size ) return TRUE else return FALSE MaxHeap Insert ( heap, item, n ) ::= if ( !HeapFull ( heap, n ) ) insert item into heap and

return the resulting heap else return error

Page 17: §3  Binary Tree Traversals                                      ——  visit each node exactly once

structure MaxHeap is ( continued )functions: Boolean HeapEmpty ( heap, n ) ::= if ( n > 0 ) return TRUE else return FALSE Element Delete ( heap, n ) ::= if ( !HeapEmpty ( heap, n ) ) return one instance of

the largest element in the heap and remove it from the heap

else return errorend MaxHeap

§6 Heaps

Obviously we can use max \ min heapsto represent this kind of queue.

Page 18: §3  Binary Tree Traversals                                      ——  visit each node exactly once

2. Representation of Heap Structure Property:

【 Definition 】 A binary tree with n nodes and height h is complete iff its nodes correspond to the nodes numbered from 1 to n in the perfect binary tree of height h.

4

8 9

5

10 11

6

12 13

7

14 15

2 3

1

A complete binary tree of height h has between

and nodes.

2h

2h+1 1 h = log N

Array Representation : heap [ n + 1 ] ( heap [ 0 ] is not used)

D

H I

E

J

F G

B C

ABT 0 1

A2B

3C

4D

5E

6F

7G

8H

9I

10J

11 12 13

Page 19: §3  Binary Tree Traversals                                      ——  visit each node exactly once

【 Lemma 】 If a complete binary tree with n nodes is represented sequentially, then for any node with index i, 1 i n, we have:

ni

niiichildright

ni

niiichildleft

i

iiiparent

12 ifNone

12 if12)(_ ofindex (3)

2 ifNone

2 if2)(_ ofindex (2)

1 ifNone

1 if2)( ofindex (1)

Page 20: §3  Binary Tree Traversals                                      ——  visit each node exactly once

Representation #define MAX_ELEMENTS 200#define HEAP_FULL(n) (n == MAX_ELEMENTS - 1)#define HEAP_EMPTY(n) (!n)

typedef struct {int key;

/* other fields */} element;element heap [MAX_ELEMENTS ];int n = 0;

Page 21: §3  Binary Tree Traversals                                      ——  visit each node exactly once

3. Basic Heap Operations:

Push (Insertion )

10

12

15

20

[1]

[2] [3]

[4]

18[5] [6]

Sketch of the idea:

The only possible position for a new node

since a heap must be a complete binary tree.

Case 1 : item = 21

21

20 21<

Case 2 : item = 17

17

20 17>

17

20

10 17<

Case 3 : item = 9 20 9>

9

10 9>

9

10

§6 Heaps

Page 22: §3  Binary Tree Traversals                                      ——  visit each node exactly once

/* heap[ 0 ] is not used. */ void Push( element item, int *n ) {/* insert intem into a min heap of current size *n */ int i;

if ( HEAP_FULL( *n ) ) { fprintf(stderr, “The heap is full.\n" ); return;

}

i = ++(*n) while ( i != 1 && item.key < heap[i / 2].key) { heap[ i ] = heap [ i / 2]; i /= 2; } heap[ i ] = item; }

Percolate up

Faster than swap

H->Element[ 0 ] is a sentinel that is no larger

than the minimum element in the heap.

T (N) = O ( log N )

§6 Heaps

Page 23: §3  Binary Tree Traversals                                      ——  visit each node exactly once

Pop (DeleteMin)

Sketch of the idea:

10

12

15

20

[1]

[2] [3]

[4]

18[5]

The node which must beremoved to keep a

complete binary tree.

move 18 up to the root18

find the smaller child of 18 12 18<18

12

15 18<18

15

Ah! That’s simple --we only have to delete

the root node ...And re-arrange

the rest of the tree so that it’s still a min heap.

T (N) = O ( log N )

§6 Heaps

Page 24: §3  Binary Tree Traversals                                      ——  visit each node exactly once

element Pop( int *n) {/* delete element with the lowest key from the min heap */

int parent, child; element item, temp; if ( HEAP_EMPTY( *n ) ) {

fprintf(stderr, “The heap is empty.\n" ); exit(EXIT_FAILURE);

} item = heap[1]; temp = heap[(*n)--]; parent = 1; child = 2; while (child <= *n) { if (child < *n && heap[child].key > heap[child + 1].key) child++; if (temp.key <= heap[child].key) break; heap[parenet] = heap[child]; parent = child; child *= 2; } heap[parent] = temp; return item;}

Percolate down

What if this condition is

omitted?

Page 25: §3  Binary Tree Traversals                                      ——  visit each node exactly once

4. Applications of Priority Queues

〖 Example 〗 Given a list of N elements and an integer k. Find the kth largest element.

How many methods can you think of to solve this problem? What are

their complexities?

§6 Heaps

Page 26: §3  Binary Tree Traversals                                      ——  visit each node exactly once

Homework-3(cont.)

• P211 #1 , #3

• P211 #6. (1). 见书 .(2).画出输入是Figure5.16时的栈状态变化示意图 .

• P215 #2

• P221 #1

• P229 #1, #4