Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Expression Trees

Similar presentations


Presentation on theme: "Binary Expression Trees"— Presentation transcript:

1 Binary Expression Trees
(a data structure used to store algebraic expressions) infix expression: a / b + (c - d) * e parenthesize fully: ((a / b) + ((c - d) * e)) **Each binary expression (within parentheses) can be represented by a tree where the root is the operator and the children are the operands.** + / * a b e c d

2 Perform a preorder traversal on above tree:
+ / * a b e c d Perform a preorder traversal on above tree: + / a b * - c d e Perform a postorder traversal on above tree: a b / c d - e * +

3 + / * a b e c d Write pseudocode for a recursive traversal, similar to thestandard inorder traversal, to display the infix expression fully parenthesized. private void displayInfix(curr) // requires all tokens to be chars {if (isLeaf(curr) print curr.data; else {print '('; displayInfix(curr.left); print curr.data; displayInfix(curr.right); print ')';}

4 Write pseudocode for a recursive method that evaluates a binary expression tree.
private int evalTree(curr) //assumes operands are strings { if isLeaf(curr) return Integer.parseInt(curr.data); else { switch curr.data case '*': return evalTree(curr.left) * evalTree(curr.left): break; case '/': return evalTree(curr.left) / evalTree(curr.left): case '+': return evalTree(curr.left) + evalTree(curr.left): case '-': return evalTree(curr.left) - evalTree(curr.left): }


Download ppt "Binary Expression Trees"

Similar presentations


Ads by Google