Difference Between Sums of Odd Level and Even Level Nodes of a Binary Tree using JavaScript
Last Updated :
27 Jun, 2024
Given a Binary Tree, our task is to find the difference between the sum of nodes at odd level and the sum of nodes at even level using JavaScript.
Example:
Input: 15
/ \
12 16
/ \ \
11 14 18
/ / \
13 17 19
Output: -19
Explanation: In the above tree,
sum of nodes at odd level is (15 + 11 + 14 + 18)
which is 58. And sum of nodes at even level is
(12 + 16 + 13 + 17 + 19) which is 77.
The output for following tree should be
58 – 77 which is -19.
These are the following approaches:
We will explore all the above methods along with their basic implementation with the help of examples.
Using Recursive Depth-First Search (DFS)
In this approach we use recursion to perform a depth-first traversal (DFS) of the binary tree. For each node, we calculate the difference between the sums of its odd-level and even-level descendant nodes. The difference for each node is given by the node's value minus the differences calculated for its left and right subtrees.
Example: In this example we are using Recursive Depth-First Search (DFS) to find the difference between sums of odd level and even level nodes of a Binary Tree
JavaScript
// Definition of a binary tree node
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Recursive function to calculate
// the level difference
function getLevelDiff(node) {
// Base case: if the node is null,
// return 0
if (node === null) {
return 0;
}
// Calculate the difference for
// the left and right subtrees
let leftDiff = getLevelDiff(node.left);
let rightDiff = getLevelDiff(node.right);
// Return the current node's value
// minus the differences of the subtrees
return node.data - leftDiff - rightDiff;
}
// Example usage
let root = new Node(15);
root.left = new Node(12);
root.right = new Node(16);
root.left.left = new Node(11);
root.left.right = new Node(14);
root.left.right.left = new Node(13);
root.right.right = new Node(18);
root.right.right.right = new Node(19);
root.right.right.left = new Node(17);
console.log(
"Difference between sums of odd level and even level nodes: "
+ getLevelDiff(root));
OutputDifference between sums of odd level and even level nodes: -19
Time Complexity: O(N) where N is the number of nodes in the binary tree.
Auxiliary Space: O(h) where h is height of the binary tree due to recursion call.
Using Level Order Traversal
In this approach we use a queue to perform level order traversal (BFS) of the binary tree. First, we maintain two sums, one for nodes at odd levels and another for nodes at even levels. During the traversal, we keep track of the current level and add node values to the appropriate sum based on whether the level is odd or even. Finally, we calculate the difference between the sums of odd level nodes and even level nodes.
Example: In this example we are using Level Order Traversal (BFS) to find the difference between sums of odd level and even level nodes of a Binary Tree.
JavaScript
// Definition of a binary tree node
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to find the difference between
// sums of odd level and even level nodes
function evenOddLevelDifference(root) {
if (root === null) {
return 0;
}
// Queue for level order traversal
let queue = [];
queue.push(root);
let oddSum = 0, evenSum = 0;
let level = 0;
while (queue.length > 0) {
let size = queue.length;
level++;
// Traverse all nodes at the
// current level
while (size > 0) {
let node = queue.shift();
// Add node value to the
// appropriate sum
if (level % 2 === 0) {
evenSum += node.data;
} else {
oddSum += node.data;
}
// Add left and right
// children to the queue
if (node.left !== null) {
queue.push(node.left);
}
if (node.right !== null) {
queue.push(node.right);
}
size--;
}
}
return oddSum - evenSum;
}
// Example usage
let root = new Node(15);
root.left = new Node(12);
root.right = new Node(16);
root.left.left = new Node(11);
root.left.right = new Node(14);
root.left.right.left = new Node(13);
root.right.right = new Node(18);
root.right.right.right = new Node(19);
root.right.right.left = new Node(17);
console.log(
"Difference between sums of odd level and even level nodes: "
+ evenOddLevelDifference(root));
OutputDifference between sums of odd level and even level nodes: -19
Time Complexity: O(N) where N is the number of nodes in the binary tree.
Auxiliary Space: O(N) where N is the number of nodes in the binary tree.
Similar Reads
Find the maximum path sum between two leaves of a binary tree using JavaScript
Given the root of a binary tree, return the maximum path sum of any non-empty path. A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to p
6 min read
Find the Distance Between Two Nodes in the Binary Tree using JavaScript
Given two nodes, our task is to find the distance between two nodes in a binary tree using JavaScript, no parent pointers are given. The distance between two nodes is the minimum number of edges to be traversed to reach one node from another. Examples: Input: Binary Tree as described above in diagra
5 min read
Find the Preorder Successor of a Given Node in a Binary Tree using JavaScript
The Preorder successor of a given node is a node that occurs after the given node in the preorder traversal of the binary tree. The preorder traversal is a traversal in which the root node is visited first, then the left child, and then the right child. Example: The pre-order successor of a binary t
2 min read
Count the Number of Nodes in a Complete Binary tree using JavaScript
We need to count the number of the nodes in the complete binary tree using JavaScript. The complete binary tree is a binary tree in which every level then except possibly the last, is completely filled and all the nodes are as far left as possible. There are several approaches for counting the numbe
4 min read
JavaScript Program for Rightmost and Leftmost Node of a Binary Tree
A binary tree is a fundamental data structure consisting of nodes, each with at most two children: a left child and a right child. The topmost node is called the root. Binary trees support operations such as insertion, deletion, and various traversal methods like in-order, pre-order, and post-order
3 min read
Sum of Squares of Even Numbers in an Array using JavaScript
JavaScript program allows us to compute the sum of squares of even numbers within a given array. The task involves iterating through the array, identifying even numbers, squaring them, and summing up the squares. There are several approaches to find the sum of the square of even numbers in an array
2 min read
Sum of Squares of Odd Numbers in an Array in JavaScript
The task involves iterating through the array, identifying odd numbers, squaring them, and summing up the squares. The different approaches to accomplish this task are listed below.Table of ContentIterative ApproachUsing Array MethodsUsing map and reduce MethodsIterative ApproachIn this approach, we
3 min read
Convert a Binary Tree to a Binary Search Tree using JavaScript
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that it keeps the original structure of the Binary Tree. Example: To demonstrate the conversion of the Binary Tree to the Binary Search Tree.Input: 10 / \ 2 7 / \ 8 4Output: 8 / \ 4 10 /
2 min read
JavaScript Program to Delete all Nodes of a Binary Search Tree
A Binary Search Tree (BST) is a type of binary tree where each node has at most two children referred to as the left child and the right child. The value of the left child node is less than the value of the current node and the value of the right child node is greater than the value of the current n
5 min read
Print the nodes having exactly one child in a Binary tree using JavaScript
Given a binary tree, our task is to return the number of nodes in the Binary tree that have at least one child otherwise return â-1â if no such node exists. Examples: Input: 1 / \ 2 3 / \ 4 5 / 6Output: 3Explanation:There are three nodes in the Binary tree that have at least one child that are 1,2,4
4 min read