Today’s announcements: ◮ PA1 review Oct 2, 18:15-20:15 ICCS X050 ◮ HW2 due Oct 4, 23:59 ◮ MT1 Oct 10, 19:00-21:00 CIRS 1250 Today’s Plan ◮ Rooted Trees Warm up: What is the maximum number of nodes in a binary tree of height h ? 1 / 9
Restricted branching d -ary: every node has at most d children ( binary if d = 2) A Recursive def: B C D E F G H I J K L full d -ary: every node has d or 0 children. perfect d -ary: as many nodes as possible for its height (each level filled in) complete d -ary: each level except possibly the deepest is filled in, all nodes in the deepest level are as far left 1 as possible 1 requires ordered tree 2 / 9
Number of nodes in perfect binary tree of height h What is a recursive definition of height of a binary tree? r height( T ) is: a b T a T b (What is a recursive definition of a binary tree?) Number of nodes N ( h ) in a perfect binary tree of height h ? 3 / 9
Ordered Binary Trees A B G C E H J An ordered binary tree is ∅ D F ∅ I ∅ ∅ K ∅ ∅ ∅ ∅ ∅ ∅ L ∅ ◮ empty, or ◮ root with left and right ordered binary subtrees ∅ ∅ How many empty trees hang onto an ordered binary tree with n nodes? 4 / 9
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 / 9
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 / 9
Euler Tree Tour: The all-in-one traversal f g b pre v post a in d i L R c e h f f f g g g b b b a a a i i i d d d c e c e c e h h h 7 / 9
Applications Expression Evaluation double eval( Node * x ) { × If (x != null) { lg ∧ double a = eval(x->left); / 2 − double b = eval(x->right); 8 16 2 }} Tree Copy Tree Clear 8 / 9
Level (Depth) order a void levelOrder( ) { c b If( root == NULL) return; e d f g j h i }} 9 / 9
Recommend
More recommend