Tree traversals Todays announcements: MT1 Feb 4, 7-9:00p WOOD 2 - - PowerPoint PPT Presentation

tree traversals
SMART_READER_LITE
LIVE PREVIEW

Tree traversals Todays announcements: MT1 Feb 4, 7-9:00p WOOD 2 - - PowerPoint PPT Presentation

Tree traversals Todays announcements: MT1 Feb 4, 7-9:00p WOOD 2 HW2 out, due Feb 5, 11:59p Todays Plan Trees and their traversals Warm up: What is the number of nodes N ( h ) in a perfect binary tree of height h ? 1 / 8 A


slide-1
SLIDE 1

Tree traversals

Today’s announcements:

◮ MT1 Feb 4, 7-9:00p WOOD 2 ◮ HW2 out, due Feb 5, 11:59p

Today’s Plan

◮ Trees and their traversals

Warm up: What is the number of nodes N(h) in a perfect binary tree of height h?

1 / 8

slide-2
SLIDE 2

Ordered Binary Trees

C E B J G A F H I K L D ∅ ∅ ∅ ∅ ∅ ∅ ∅ ∅ ∅ ∅ ∅ ∅ ∅

An ordered binary tree is

◮ empty (∅), or ◮ root node with left and right ordered binary subtrees

Given height h binary tree,

◮ max # nodes = ◮ max # leaves = ◮ max # empty slots =

2 / 8

slide-3
SLIDE 3

Complete binary tree

L K J I H D E B F G C A

A complete tree of height h is

TL TR

  • r

TL TR

Min/Max number of nodes in Complete(h)?

3 / 8

slide-4
SLIDE 4

Complete binary tree height

L K J I H D E B F G C A

Height of the complete binary tree with n nodes. H(1) = H(2) = · · · = H( ) = H( ) = · · · = H( ) =

4 / 8

slide-5
SLIDE 5

Ordered binary tree ADT

root ∅ dog bee emu ant cat ∅ ∅ ∅ ∅ ∅

Tree ADT

◮ insert ◮ remove ◮ traverse

template<class T> class tree { public: ... private: struct Node { T data; Node * left; Node * right; }; Node * root; ... };

5 / 8

slide-6
SLIDE 6

Traversals

2 9 5 20 15 10 7 30 17

inOrder( Node * x ) { If (x != null) { inorder(x->left); inorder(x->right); }} In order: 2, 5, 7, 9, 10, 15, 17, 20, 30

6 / 8

slide-7
SLIDE 7

Expression Evaluation

2 − ∧ / lg × 8 2 16

double eval( Node * x ) { If (x != null) { double a = eval(x->left); double b = eval(x->right); }}

Tree Copy Tree Clear

7 / 8

slide-8
SLIDE 8

Level (Depth) order

2 9 5 20 15 10 7 30 17

void levelOrder( ) { If( root == NULL) return; }}

8 / 8