- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between sums of odd level and even level nodes of a Binary Tree in Java
Problem Statement
With a given binary tree, write a program to find the difference between sum of nodes at odd level and even level. Assume root at level 1, left/right child of root at level 2 and so on.
Example
5 / \ 2 6 / \ \ 1 4 8 / / \ 3 7 9 Sum of nodes at odd level = 5 + 1 + 4 + 8 = 18 Sum of nodes at even level = 2 + 6 + 3 + 7 + 9 = 27 Difference = -9.
Solution
Use Recursive Traversal. During traversal, return the difference of root node and its left and right child.
Example
Following is the program in Java to find the required output.
class Node { int data; Node left, right; Node(int data){ this.data = data; this.left = this.right = null; } } public class JavaTester { public static Node getTree(){ Node root = new Node(5); root.left = new Node(2); root.right = new Node(6); root.left.left = new Node(1); root.left.right = new Node(4); root.left.right.left = new Node(3); root.right.right = new Node(8); root.right.right.right = new Node(9); root.right.right.left = new Node(7); return root; } public static int difference(Node node){ if(node == null) return 0; return node.data - difference(node.left) - difference(node.right); } public static void main(String args[]){ Node tree = getTree(); System.out.println(difference(tree)); } }
Output
-9
- Related Articles
- Difference between sums of odd position and even position nodes of a Binary Tree in Java
- Difference between sums of odd and even digits.
- Program to print nodes between two given level numbers of a binary tree using C++
- Depth of the deepest odd level node in Binary Tree in C++?
- Python Program for Difference between sums of odd and even digits
- C Program for Difference between sums of odd and even digits?
- Depth of the deepest odd level node in Binary Tree in C++ Program
- C Program for the Difference between sums of odd and even digits?
- Maximum Level Sum of a Binary Tree in C++
- Difference between Object level lock and Class level lock in Java
- Binary Tree Level Order Traversal in C++
- Print all odd nodes of Binary Search Tree in C++
- Print all even nodes of Binary Search Tree in C++
- Difference between system level exception and Application level exception.
- Difference Between High-Level Language and Low-Level Language

Advertisements