Data sturcture and algorithm week 8
Data sturcture and algorithm week 8
Semester – II Semester
EA2331201010152
1. Construct an expression tree for the following expression. (5+9) / (2*7)
/
/ \
+ *
/ \ / \
5 9 2 7
Explanation:
1. The main operator is the division (/). It becomes the root node of the tree.
2. The left subtree represents the numerator, which is the addition (+) of 5 and 9.
o The addition node becomes the left child of the root.
o The operands 5 and 9 become the left and right children of the addition node,
respectively.
3. The right subtree represents the denominator, which is the multiplication (*) of 2 and
7.
o The multiplication node becomes the right child of the root.
o The operands 2 and 7 become the left and right children of the multiplication
node, respectively.
This tree structure reflects the order of operations (division happens after addition and
multiplication).
A binary tree is considered balanced if the heights of the left and right subtrees of any node
differ by at most 1. This ensures efficient searching and operations in the tree.
1. Identify the Root Node: Locate the node with no parent (usually at the top).
2. Check Subtree Heights: Recursively calculate the heights of the left and right
subtrees for each node. The height of a subtree is the maximum number of edges from
the node to a leaf node (a node with no children).
3. Compare Heights: For each node, compare the absolute difference between the
heights of its left and right subtrees. If the difference is greater than 1, the tree is not
balanced.
EA2331201010152
4. Base Case: If a node is a leaf node (has no children), its height is considered 0.
Example:
If the root node in the image has a left subtree height of 2 and a right subtree height of 3, the
tree is not balanced (absolute difference of 1 exceeds the limit).
EA2331201010152