![]() |
VOOZH | about |
Given two binary trees, the task is to find the sum of the absolute differences between the right view of binary trees.
Examples:
Input: Tree 1:
10
/ \
5 20
/ \ \
4 7 30Tree 2:
50
/ \
25 60
/ \ / \
20 30 55 70Output: 120
Explanation: For Tree 1, the right view nodes are 10, 20, and 30. Therefore, the right view sum is 10 + 20 + 30 = 60, and For Tree 2, the right view nodes are 50, 60, and 70. Therefore, the right view sum is 50 + 60 + 70 = 180. The absolute difference between the right view sum of Tree 1 and Tree 2 is |180 - 60| = 120. Therefore, the output is 120.Input: Tree 1:
1
/ \
2 3
/ \ / \
4 5 6 7Tree 2:
6
/ \
7 5
/ \ / \
1 5 4 3Output: 3
Explanation: Right view sum of Tree 1: 1 + 3 + 7 = 11, Right view sum of Tree 2: 6 + 5 + 3 = 14. Thus |14 - 11| = 3
Approach: To solve the problem follow the below idea:
This problem requires us to calculate the sum of nodes that are visible from the right side of the binary tree and then find the absolute difference between the sums of the right view of two given binary trees. To calculate the sum of nodes that are visible from the right side of the binary tree, we can do a level-order traversal of the binary tree and for each level, we can add the rightmost node's value to the sum. We can use a queue to perform the level-order traversal of the binary tree. We first push the root node into the queue and then continue to process nodes until the queue becomes empty. For each level of the binary tree, we set a flag to indicate that the next node to be processed is the rightmost node. Then we pop each node from the queue and add its value to the sum if the flag is set. We then push its right and left child nodes into the queue if they exist. If we have processed all the nodes in a level, we reset the flag to indicate that the next node to be processed is the rightmost node of the next level. Once we have calculated the right view sum of both binary trees, we can find the absolute difference between them and return the result.
Steps of the approach:
Implementation of the above approach:
Absolute Difference of Right View Sums: 120
Time Complexity: O(N), where N is the total number of nodes in both trees.
Auxiliary Space: O(N)