180 likes | 249 Views
Lab 4. Due date: March 29. Linked Representation. Each binary tree node is represented as an object whose data type is binaryTreeNode . The space required by an n node binary tree is n * (space required by one node). The Struct binaryTreeNode. template <class T> struct binaryTreeNode
E N D
Lab 4 • Due date: March 29
Linked Representation • Each binary tree node is represented as an object whose data type is binaryTreeNode. • The space required by an n node binary tree is n * (space required by one node).
The StructbinaryTreeNode template <class T> structbinaryTreeNode { T element; binaryTreeNode<T> *leftChild, *rightChild; binaryTreeNode() {leftChild = rightChild = NULL;} // other constructors come here };
root a c b d f e g h leftChild element rightChild Linked Representation Example
// create a binary tree with root x binaryTreeNode<int> *x, *y, *z; y = new binaryTreeNode<int> (2); z = new binaryTreeNode<int> (3); x = new binaryTreeNode<int> (1, y, z);
visit void visit(binaryTreeNode<T> *x) {// visit node *x, just output element field. cout << x->element << ' '; treeSize++; }
Binary Tree Traversal Methods • Preorder • Inorder • Postorder • Level order
a b c Preorder Example (visit = print) a b c
Preorder Traversal template <class T> void preOrder(binaryTreeNode<T> *t) { if (t != NULL) { visit(t); preOrder(t->leftChild); preOrder(t->rightChild); } }
a b c Inorder Example (visit = print) b a c
Inorder Traversal template <class T> voidinOrder(binaryTreeNode<T> *t) { if (t != NULL) { inOrder(t->leftChild); visit(t); inOrder(t->rightChild); } }
a b c Postorder Example (visit = print) b c a
Postorder Traversal template <class T> voidpostOrder(binaryTreeNode<T> *t) { if (t != NULL) { postOrder(t->leftChild); postOrder(t->rightChild); visit(t); } }
Level Order Let t be the tree root. while (t != NULL) { visit t and put its children on a FIFO queue; if FIFO queue is empty, set t = NULL; otherwise, pop a node from the FIFO queue and call it t; }
queue<binaryTreeNode<T>*> q; while (t != NULL) { visit(t); // visit t // put t's children on queue if (t->leftChild != NULL) q.push(t->leftChild); if (t->rightChild != NULL) q.push(t->rightChild); // get next node to visit t = q.front(); if(!q.empty()) q.pop(); }
a b c f e d j g h i Level-Order Example (visit = print) a b c d e f g h i j
Implement functions • Preorder traversal • In-order traversal • Post-order traversal • Level-order traversal • And test your program using previous example