In this project, we will use a BST hands-on assignment to help us understand the Binary Tree structure.
Guidelines
A – Build a binary tree representing the following arithmetic expression:
((((3+1) ∗3)/((9−5)+2))−((3 ∗(7−4))+6))
Solution the Binary Tree structure
To build a binary tree representing the arithmetic expression ((((3+1) ∗3)/((9−5)+2))−((3 ∗(7−4))+6)), I will:
First, Identify the operators and operands in the expression.
Operators: +, ∗, /, −, +, ∗
Operands: 3, 1, 3, 9, 5, 2, 7, 4, 6
And convert my expression to postfix notation, also known as Reverse Polish Notation.
3 1 + 3 ∗ 9 5 − 2 + / 3 7 4 − ∗ 6 + −
Lastly, I will create my binary tree by reading the postfix expression from left to right. Each operand becomes a leaf node, and each operator becomes an internal node with its left and right subtrees as its operands.
–
/ \
/ \
/ \
÷ +
/ \ / \
* + * 6
/ \ / \
3 + 3 –
/ \ / \
1 * 7 4
/ \
9 2
2 – Given the Tree below. Write two arrays showing both Preorder and Post-order traversals.
27
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
/ \
14 35
/ \ / \
10 19 31 42
Solution the Binary Tree structure
Preorder traversal: 27, 14, 10, 19, 35, 31, 42.
Postorder traversal: 10, 19, 14, 31, 42, 35, 27