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.
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
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:
Time Complexity: O(N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Difference between sums of odd level and even level nodes of a Binary Tree
- Difference between sums of odd position and even position nodes for each level of a Binary Tree
- Count nodes from all lower levels smaller than minimum valued node of current level for every level in a Binary Tree
- Difference between sums of odd level and even level nodes in an N-ary Tree
- Print odd positioned nodes of odd levels in level order of the given binary tree
- Print even positioned nodes of odd levels in level order of the given binary tree
- Print odd positioned nodes of even levels in level order of the given binary tree
- Print even positioned nodes of even levels in level order of the given binary tree
- Print levels with odd number of nodes and even number of nodes
- Minimum valued node having maximum depth in an N-ary Tree
- Maximum decimal equivalent possible among all connected components of a Binary Valued Graph
- Hexadecimal equivalents in Binary Valued Graph
- Sum of all the child nodes with even parent values in a Binary Tree
- Sum of all the child nodes with even grandparents in a Binary Tree
- Difference between Binary Tree and Binary Search Tree
- Minimum difference between any two weighted nodes in Sum Tree of the given Tree
- Create loops of even and odd values in a binary tree
- Sum of all odd nodes in the path connecting two given nodes
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Sink Odd nodes in Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : Amal Kumar Choubey