![]() |
VOOZH | about |
Given a binary tree, the task is to find the absolute difference between the even valued and the odd valued nodes in a binary tree.
Examples:
Input: 5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9 Output: 5 Explanation: Sum of the odd value nodes is: 5 + 1 + 3 + 7 + 9 = 25 Sum of the even value nodes is: 2 + 6 + 4 + 8 = 20 Absolute difference = (25 – 20) = 5. Input: 4 / \ 1 4 / \ \ 7 2 6 Output: 8
Approach:
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
5
Time Complexity: O(N) where N is the number of nodes in given Binary Tree, as it does a simple traversal of the tree.
Auxiliary Space: O(h) where h is the height of given Binary Tree due to Recursion.
Another Approach (Iterative):
We can solve this problem by level order traversal using queue.
Below is the implementation of above approach:
5