Tree
Tree
Tree Traversals
It's unclear how we should print a tree. Top to bottom? Left to right? A tree traversal is a specific order in which to trace the nodes of a tree. There are 3 common tree traversals. 1. in-order: left, root, right 2. pre-order: root, left, right 3. post-order: left, right, root This order is applied recursively. So for in-order, we must print each subtree's left branch before we print its root. Note "pre" and "post" refer to when we visit the root.
in-order: (left, root, right) 3, 5, 6, 7, 10, 12, 13, 15, 16, 18, 20, 23 pre-order: (root, left, right) 15, 5, 3, 12, 10, 6, 7, 13, 16, 20, 18, 23 post-order: (left, right, root) 3, 7, 6, 10, 13, 12, 5, 18, 23, 20, 16, 15
In-Order Traversal
The in-order traversal is probably the easiest to see, because it sorts the values from smallest to largest.
template <typename T> void Tree<T> :: printInOrder (std::ostream& out, TreeNode<T>* rootNode) { ostream is a name in std if (rootNode != NULL) { namespace. printInOrder (out, rootNode->left); The std:: means that we dont out << (rootNode->data) << "\n"; have to use the std namespace to use this class. printInOrder (out, rootNode->right); } return; 2 In-order: 1 2 3 }
1 3
Pre-Order Traversal
Pre-order traversal prints in order: root, left, right. template <typename T> void Tree<T>::printPreOrder(std::ostream& out, TreeNode<T>* rootNode) { if (rootNode != NULL) { out << (rootNode->data) << "\n"; printPreOrder (out, rootNode->left); printPreOrder (out, rootNode->right); } return; } 2
Pre-order: 2 1 3 1 3
Post-Order Traversal
Post-order traversal prints in order: left, right, root. It is also called a depth-first search. template <typename T> void Tree<T>::printPostOrder(std::ostream& out, TreeNode<T>* rootNode) { if (rootNode != NULL) { printPostOrder (out, rootNode->left); printPostOrder (out, rootNode->right); out << (rootNode->data) << "\n"; } return; 2 } Post-order: 1 3 2
1 3
In-order: Chewbacca, Han, Lando, Leia, Luke, Obi, Vader, Yoda Pre-order: Luke, Han, Chewbacca, Leia, Lando, Vader, Obi, Yoda Post-order: Chewbacca, Lando, Leia, Han, Obi, Yoda, Vader, Luke
Summary of Trees
Compared to vectors and linked lists, trees have a running time somewhere in between the best and worst.
Vector Insert / Erase (at known position) Indexing (look up element) Finding an Element O(N) O(1) O(N) Linked List Binary Tree O(1) O(N) O(N) O(h) O(h) O(h)
The height h = N-1 = O(N). In the best case, the tree is perfectly balanced.
Fact: A completely full tree with height h has N = 2h+1-1 nodes. Solving for h gives h = log(N+1)-1 = O(logN). What's the average height?
Average Height
Let's look at a randomly built tree: a tree built from random numbers inserted in random order. Theorem The average height h of an randomly built tree with N nodes satisfies
N 1 2 h 2( + 1) 1 + 2 i =1 i N
(ln 1) = 2
So on average, h = O(logN). So tree operations are on average O(logN).