Trees
Containers we have studied so far are linear. To represent nonlinear, i.e. hierarchal data we use trees. Nonlinear Containers root node leaf edge
Tree Terminology root parent node child node leaf (no children) sub-tree Binary Tree: two child nodes Oct-tree: eight child nodes, etc. Huffman Tree: binary tree of codes of characters that might appear in the encoded message
Tree Terminology, cont’d Complete Tree Incomplete Tree Full Tree
If the tree is empty (i.e. leaf) then return Else for each child node traverse sub-tree end for End if Tree Traversal (Recursive)
Preorder: process root node, traverse left sub-tree, traverse right sub-tree Node processing order: a b d e c Binary Tree Preorder Traversal a bc de
Inorder: traverse left sub-tree, process root node, traverse right sub-tree Node processing order: d b e a c Binary Tree Inorder Traversal a bc de
Postorder: traverse left sub-tree, traverse right sub-tree, process root node Node processing order: d e b c a Binary Tree Postorder Traversal a bc de
Binary Tree Node data leftright data leftright data leftright Root Node Left Child Node Right Child Node
Task: Build a tree for an arithmetic expression and evaluate it. What kind of tree? Binary, full Why Binary? Because arithmetic operations require two operands, e.g. a+b Why Full? Because arithmetic operations require exactly two operands Exercise: Arithmetic Express. Tree
10+3*4/(2-1) Nodes: operations +,-,*,/ Leafs: operands Arithmetic Expression Tree / * 3 nodes leafs
For simplicity assume single-digit operands, no parenthesis, well-formed expressions e.g.:1+5*3-4/2 1)Set treeRoot = NULL 2)Set currentNode = treeRoot 3)Scan expression from left 4)If you find 0..9 then -Create newLeaf node, set its value to If the currentNode = NULL then treeRoot = currentNode = newLeaf else currentNode->Right = newLeaf 5)If you find + or – (or *,/ and currentNode->Right = NULL) then -Create newRoot node, set its value the operation found -Set newRoot->Left = treeRoot -Set treeRoot = newRoot -Set currentNode = newRoot 6)If you find * or / then -create newChild node, set its value to * or / -Set newChild->Left = currentNode->Right -Set currentNode ->Right = newChild -Set currentNode = newChild 7)Until you reach the end of string Tree Construction Algorithm
Recursive process: ExpressionValue = ValueOf(treeRoot->Left) {treeRoot->Operation} ValueOf(treeRoot->Right) Expression Evaluation Algorithm op leftright
template struct TreeNode { TreeNode(const T& value, TreeNode * left = NULL, TreeNode * right = NULL) { Value = value; Left = left; Right = right; } T Value; TreeNode * Left; TreeNode * Right; bool IsLeaf() const { return Left == NULL && Right == NULL; } }; Declare TreeNode Structure
Read chapter 8, prepare for quiz next class. I will randomly question 10 students. Correct answer earns 1%, incorrect earns -1%.Assignment