Sum of Left leaves in Binary Tree using JavaScript
Last Updated :
08 May, 2024
Calculating the sum of all left leaves in a binary tree is a common task that helps in understanding tree traversal techniques. A left leaf is defined as a leaf node that is the left child of its parent node. This problem can serve various purposes, such as evaluating symmetry in data structures or specific tree-based calculations.
Problem Description:
In this problem, we need to identify all the left leaves in a binary tree and calculate their cumulative sum. A leaf is a node with no children, and a left leaf is a leaf that is also a left child of its parent.
Example: Consider the following binary tree:
3
/ \
9 20
/ \
15 7
In this tree, the only left leaf is the node with value 9. Thus, the sum of the left leaves is 9.
There are several methods in JavaScript to find the sum of left leaves in Binary Tree which are as follows:
Recursive Method
We will use a recursive function to traverse the tree and add the values of all left leaves:
- The function will check if a node is a leaf node.
- If it's a left leaf (i.e., a left child and a leaf), its value will be added to the sum.
- Recursive calls are made for both left and right children.
Example: To demonstrate finding the sum of left leaves in BInary tree using recursion in JavaScript.
JavaScript
class TreeNode {
constructor(value = 0, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
function sumOfLeftLeaves(root, isLeft = false) {
if (!root) return 0;
if (!root.left && !root.right) {
return isLeft ? root.value : 0;
}
return sumOfLeftLeaves(root.left, true)
+
sumOfLeftLeaves(root.right, false);
}
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right =
new TreeNode(20, new TreeNode(15), new TreeNode(7));
root.right.left.left = new TreeNode(10);
root.right.left.left.left = new TreeNode(11);
// Calculate sum of left leaves
console.log(sumOfLeftLeaves(root));
Time Complexity:
- Best Case: O(1) (constant time)
- Worst Case: O(n) (linear time)
Space Complexity: O(h), where h is the height of the tree.
Iterative Method Using Stack
This approach uses a stack to simulate the recursive behavior of the tree traversal:
- Each node along with its 'leftness' status is pushed to the stack.
- Nodes are popped from the stack, and if a node is a left leaf, its value is added to the sum.
- Children nodes are then added to the stack accordingly.
Example: To demonstrate finding the sum of left leaves in Binary tree using iteration with stack in JavaScript.
JavaScript
function sumOfLeftLeavesIterative(root) {
if (!root) return 0;
let sum = 0;
const stack = [{ node: root, isLeft: false }];
while (stack.length) {
const { node, isLeft } = stack.pop();
if (!node.left && !node.right && isLeft) {
sum += node.value;
}
if (node.right) stack
.push({ node: node.right, isLeft: false });
if (node.left) stack
.push({ node: node.left, isLeft: true });
}
return sum;
}
class TreeNode {
constructor(value = 0, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right =
new TreeNode(20, new TreeNode(15), new TreeNode(7));
root.right.left.left = new TreeNode(10);
root.right.left.left.left = new TreeNode(11);
// Calculate sum of left leaves
console.log(sumOfLeftLeavesIterative(root));
Time Complexity:
- Best Case: O(1) (constant time)
- Worst Case: O(n) (linear time)
Space Complexity: O(n), where n is the number of nodes in the tree.
BFS with Queue
Using a breadth-first search approach, we process nodes level by level, which can be efficient in scenarios where the tree is balanced or nearly balanced:
- A queue is used to store the nodes along with their 'leftness' status.
- Nodes are dequeued and checked; if a node is a left leaf, its value is added to the sum.
- This method can potentially reduce the need to visit all nodes if combined with other conditions or optimizations, such as early stopping if a certain condition is met.
Example: To demonstrate finding the sum of left leaves in Binary tree using breadth first search with queue in JavaScript.
JavaScript
function sumOfLeftLeavesBFS(root) {
if (!root) return 0;
let sum = 0;
const queue = [{ node: root, isLeft: false }];
while (queue.length) {
const { node, isLeft } = queue
.shift();
if (!node.left && !node.right && isLeft) {
sum += node.value;
}
if (node.right) queue
.push({ node: node.right, isLeft: false });
if (node.left) queue
.push({ node: node.left, isLeft: true });
}
return sum;
}
class TreeNode {
constructor(value = 0, left = null, right = null) {
this.value = value;
this.left = left;
this.right = right;
}
}
const root = new TreeNode(3);
root.left = new TreeNode(9);
root.right =
new TreeNode(20, new TreeNode(15), new TreeNode(7));
// Calculate sum of left leaves
console.log(sumOfLeftLeavesBFS(root));
Time Complexity:
- Best Case: O(1) (constant time)
- Worst Case: O(n) (linear time)
Space Complexity: O(n), where n is the number of nodes in the tree.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read