CPSC 221

Tree Traversals

Today

Announcements

  • Examlet 4 runs Thursday to Sunday: stacks and queues, array resizing, merge sort and recurrences, the sorting lower bound. No trees.
  • PEX5 (trees and traversals) comes out tonight


Where we’re going

  • Finishing up: implementation, null pointers, bounds
  • Traversals

Contemplating implementation

root 5 3 9 1 4 6

Tree ADT:

  • insert
  • remove
  • traverse
template<class T>
class tree {
public:  // discuss later
private:
    struct Node {
        T data;
        Node * left;
        Node * right;
    };
    Node * root;  // + more?
};

Theorem

Theorem: Our implementation of an \(n\) item binary tree has _______ null pointers.

root 5 3 9 1 4 6

Practice 1

  1. Draw a FULL tree with 9 nodes. Is it the same as your neighbour’s?

Practice 2

  1. Draw a COMPLETE tree with 12 nodes. Is it the same as your neighbour’s?

Practice 3

3a) Give an upper bound for the number of nodes in a tree of height h:



3b) Give a lower bound for the height of a tree containing n nodes:

Practice 4

  1. Give upper and lower bounds for the number of nodes in a complete tree of height h:

Tree traversal:

… a scheme for visiting every node

+ - / b c * d e

Traversal: a scheme for visiting every node

10 12 15 3 9 7 20 30 8

_____Order:   3, 12, 9, 7, 10, 15, 30, 20, 8

_____Order:

_____Order:

template<class T>
void tree<T>::_______Order(Node * croot) {
    if (croot != nullptr) {

        ___Order(croot->left);

        ___Order(croot->right);

    }
}
template<class T>
void tree<T>::_______Order(Node * croot) {
    if (croot != nullptr) {

        ___Order(croot->left);

        ___Order(croot->right);

    }
}
template<class T>
void tree<T>::_______Order(Node * croot) {
    if (croot != nullptr) {

        ___Order(croot->left);

        ___Order(croot->right);

    }
}

Traversal shortcuts… Euler tour

Pre Post In TL TR
a b c d f e i h j

Mystery function: what’s a good name?

38 13 51 10 25 40 84 12 37 66 89 95

RT:

template<class T>
void tree<T>::__________(Node * croot) {
    if (croot != nullptr) {
        __________(croot->left);
        __________(croot->right);
        delete croot;
        croot = nullptr;
    }
}

Traversals: a broader view…

38 13 51 10 25 40 84 12 37 66 89 95
template<class T>
Node * tree<T>::copy(Node * croot) {








}