Tree traversals Applications February 01 2019 Cinda Heeren
Tree traversals Applications February 01, 2019 Cinda Heeren / Will Evans / Geoffrey Tien 1
How to level-order? • Use iteration and a queue to perform level-order traversal – Initialize an empty queue, and enqueue the root – while queue is not empty • save/visit and dequeue front item • enqueue the children of removed item (remember to check if null!) 41 front 33 21 41 33 87 21 74 36 45 78 25 87 74 78 back 45 36 25 What would the traversal look like if we used a stack instead of a queue? February 01, 2019 Cinda Heeren / Will Evans / Geoffrey Tien 2
Pre-order traversal What is it used for? • Pre-order gives information about the structure of a tree – the root is always the first node visited • e. g. recursive copy – can be used in a copy constructor, or assignment operator Node* copy(const Node* other) { Node* nd = nullptr; if (other != nullptr) { nd = new Node(other->data); nd->left = copy(other->left); nd->right = copy(other->right); } return nd; } other nd 41 41 33 33 87 87 74 74 February 01, 2019 Cinda Heeren / Will Evans / Geoffrey Tien 3
Post-order traversal • Also gives structure information – root is always the last node visited • Useful for tree computations – e. g. height, from previous lesson – recursive deallocation – can be used in destructor and assignment operator void clear(Node*& nd) { if (nd != nullptr) { clear(nd->left); clear(nd->right); delete nd; nd = nullptr; } } nd 41 33 87 74 February 01, 2019 Cinda Heeren / Will Evans / Geoffrey Tien 4
In-order traversal • What will be printed by an in-order traversal of the tree? in. Order(nd->leftchild); 17 visit(nd); in. Order(nd->rightchild); 9 27 6 16 12 February 01, 2019 20 How can we construct a tree with this property anyway? Cinda Heeren / Will Evans / Geoffrey Tien 31 39 5
Ordered binary trees Binary search tree • A binary search tree is a binary tree with a special property – For all nodes in the tree: • All nodes in a left subtree have labels less than the label of the subtree's root • All nodes in a right subtree have labels greater than or equal to the label of the subtree's root • Binary search trees are fully ordered February 01, 2019 Cinda Heeren / Will Evans / Geoffrey Tien 6
Readings for this lesson • Carrano & Henry – Chapter 15. 1 – 15. 2 (Tree terminology, binary trees & traversals) • Next class: – Carrano & Henry: Chapter 15. 3 (Binary search tree) February 01, 2019 Cinda Heeren / Will Evans / Geoffrey Tien 7
- Slides: 7