VOOZH about

URL: https://www.geeksforgeeks.org/dsa/difference-between-sum-of-even-and-odd-valued-nodes-in-a-binary-tree/

⇱ Difference between sum of even and odd valued nodes in a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Difference between sum of even and odd valued nodes in a Binary Tree

Last Updated : 21 Mar, 2023

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:

  • Traverse each node in the tree and check if the value at that node is odd or even.
  • Update oddSum and evenSum accordingly after visiting each node.
  • After complete traversal of the tree, print the absolute difference between oddSum and evenSum.

Below is the implementation of the above approach:


Output: 
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:


Output
5
Comment