Title: Expression Trees
1Expression Trees
- Another way to process expressions is to build a
parse tree during parsing - Expression tree
- An expression tree is never empty
- An interior node represents a compound
expression, consisting of an operator and its
operands - Each leaf node represents a numeric operand
- Operands of higher precedence usually appear near
bottom of tree, unless overridden in source
expression by parentheses
2Expression Trees (continued)
3Binary Tree Traversals
- Four standard types of traversals for binary
trees - Preorder traversal Visits root node, and then
traverses left subtree and right subtree in
similar way - Inorder traversal Traverses left subtree, visits
root node, and traverses right subtree - Appropriate for visiting items in a BST in sorted
order - Postorder traversal Traverses left subtree,
traverses right subtree, and visits root node - Level order traversal Beginning with level 0,
visits the nodes at each level in left-to-right
order
4Binary Tree Traversals (continued)
5Binary Tree Traversals (continued)
6Binary Tree Traversals (continued)
7Binary Tree Traversals (continued)
8Write the order in which the nodes are visited in
the binary tree shown above using In-order
traversal Pre-order traversal
Post-order traversal Breadth-first
(level-order) traversal
9A Binary Tree ADT
- Provides many common operations required for
building more specialized types of trees - Should support basic operations for creating
trees, determining if a tree is empty, and
traversing a tree - Remaining operations focus on accessing,
replacing, or removing the component parts of a
nonempty binary treeits root, left subtree, and
right subtree
10The Interface for a Binary Tree ADT
11The Interface for a Binary Tree ADT (continued)
12Processing a Binary Tree
- Many algorithms for processing binary trees
follow the trees recursive structure - Programmers are occasionally interested in the
frontier, or set of leaf nodes, of a tree - Example Frontier of parse tree for English
sentence contains the words in the sentence
13Processing a Binary Tree (continued)
- frontier expects a binary tree and returns a list
- Two base cases
- Tree is empty ? return an empty list
- Tree is a leaf node ? return a list containing
root item
14Implementing a Binary Tree
15Implementing a Binary Tree (continued)
16Implementing a Binary Tree (continued)
17The String Representation of a Tree
- __str__ can be implemented with any of the
traversals