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
A Ordered Binary Trees B G C E H J An ordered binary tree is ∅ ∅ ∅ ∅ D F I K ◮ empty ( ∅ ), or ∅ ∅ ∅ ∅ ∅ ∅ ∅ L ◮ root node with left and right ordered binary subtrees ∅ ∅ Given height h binary tree, ◮ max # nodes = ◮ max # leaves = ◮ max # empty slots = 2 / 8
Complete binary tree A complete tree of height h is or T L T R T L T R A Min/Max number of nodes in Complete( h )? B C D E F G H I J K L 3 / 8
Complete binary tree height A Height of the complete binary tree with n nodes. B C H (1) = H (2) = · · · = H ( ) = D E F G H ( ) = · · · = H ( ) = H I J K L 4 / 8
Ordered binary tree ADT template<class T> root class tree { dog public: ... emu private: bee ∅ ∅ struct Node { ant cat T data; ∅ ∅ ∅ ∅ Node * left; Tree ADT Node * right; }; ◮ insert Node * root; ◮ remove ... ◮ traverse }; 5 / 8
Traversals 10 inOrder( Node * x ) { 5 15 If (x != null) { 2 9 20 inorder(x->left); 7 17 30 inorder(x->right); }} In order: 2, 5, 7, 9, 10, 15, 17, 20, 30 6 / 8
Expression Evaluation × double eval( Node * x ) { lg ∧ If (x != null) { / 2 − double a = eval(x->left); 8 16 2 double b = eval(x->right); }} Tree Copy Tree Clear 7 / 8
Level (Depth) order 10 void levelOrder( ) { 5 15 If( root == NULL) return; 2 9 20 7 17 30 }} 8 / 8
Recommend
More recommend