Download presentation
Presentation is loading. Please wait.
Published byAmberly Philomena Merritt Modified over 8 years ago
1
Lab 4 Due date: March 29
2
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).
3
The Struct binaryTreeNode template struct binaryTreeNode { T element; binaryTreeNode *leftChild, *rightChild; binaryTreeNode() {leftChild = rightChild = NULL;} // other constructors come here };
4
Linked Representation Example a cb d f e g h leftChild element rightChild root
5
// create a binary tree with root x binaryTreeNode *x, *y, *z; y = new binaryTreeNode (2); z = new binaryTreeNode (3); x = new binaryTreeNode (1, y, z);
6
visit void visit(binaryTreeNode *x) {// visit node *x, just output element field. cout element << ' '; treeSize++; }
7
Binary Tree Traversal Methods Preorder Inorder Postorder Level order
8
Preorder Example (visit = print) a bc abc
9
Preorder Traversal template void preOrder(binaryTreeNode *t) { if (t != NULL) { visit(t); preOrder(t->leftChild); preOrder(t->rightChild); }
10
Inorder Example (visit = print) a bc bac
11
Inorder Traversal template void inOrder(binaryTreeNode *t) { if (t != NULL) { inOrder(t->leftChild); visit(t); inOrder(t->rightChild); }
12
Postorder Example (visit = print) a bc bca
13
Postorder Traversal template void postOrder(binaryTreeNode *t) { if (t != NULL) { postOrder(t->leftChild); postOrder(t->rightChild); visit(t); }
14
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; }
15
queue *> 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(); }
16
Level-Order Example (visit = print) a bc d e f g hi j abcdefghij
17
Practice create a tree as below, and test your code.
18
Implement functions Preorder traversal In-order traversal Post-order traversal Level-order traversal And test your program using previous example
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.