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
LCA in Binary Tree using JavaScript
The lowest common ancestor between two nodes n1 and n2 in a binary tree is defined as the lowest node in a Tree that has both n1 and n2 as descendants. If either n1 or n2 is not present in the tree, or if they are not connected through a common ancestor, the LCA of the binary tree is NULL. Below is
4 min read
Height of Binary Tree using JavaScript
The height of a binary tree can be defined as the maximum depth or length of the longest path from the root node to any leaf node. Below is an example to illustrate the height of the binary tree. Height of Binary tree is 3There are several approaches to find height of Binary tree using JavaScript wh
3 min read
Count all K-Sum Paths in a Binary Tree using JavaScript
Given a binary tree and a number k, our task is to find the total number of paths where the sum of the values along the path equals k. The path can start and end at any node in the tree and must go downwards means moving only from parent nodes to child nodes. ApproachDefine a class T_Node representi
2 min read
Return the Leftmost Value in the Last Row of the Binary Tree using JavaScript
Given the root of a binary tree, our task is to return the leftmost value in the last row of the binary tree in JavaScript. Here we use recursive and iterative approaches to return the leftmost value in the last row. Explanation: The image below illustrates the leftmost value in the last row of the
3 min read
JavaScript Program to Find Sum of Leaf Node in Binary Tree
Given a binary tree, We have to find the sum of all leaf nodes. A leaf node is a node that does not have any children. Example: Input binary tree: 1 / \ 2 3 / \ / \ 4 5 6 7The sum of leaf nodes would be: 4 + 5 + 6 + 7 = 22Table of Content Using recursive approachIterative Approach Using StackUsing r
3 min read
Kth Largest/Smallest Element in Binary Search Tree using JavaScript
A binary search tree is a type of binary tree in which each node has two children: left child & right child. In a Binary search tree (BST) all nodes in the left subtree have values less than the node value and all nodes in the right subtree have values greater than the node value. Different appr
4 min read
Kth Ancestor in Binary Tree using JavaScript
Given a binary tree and a node in this tree, our task is to find the k-th ancestor of the specified node in JavaScript. If no such ancestor exists, or when k exceeds the depth of the node, the function should return null. Example: Input: Node = 5, k = 2Output: 1ApproachFirst, calculate the depth of
2 min read
Insert a Node in Binary tree using JavaScript
A binary tree is a tree data structure where each node has at most two children, referred to as the left child and the right child. The topmost node is called the root. Nodes can have values or data, and the left child's value is less than the parent's value, while the right child's value is greater
3 min read
Find Distance Between Two Nodes of a Binary Tree using JavaScript
In computer science, binary trees are hierarchical data structures that consist of nodes. Each node can have two children at most - one on the leÂft side and one on the right. These structures have a top-to-bottom order. Solving for distance between any two giveÂn nodes is a problem often seÂen w
7 min read
Search a Given Key in BST using JavaScript
Given a binary search tree and a key, determine if the key is present in the tree. If the key is present, return the node containing the key otherwise, return null. Example: Input : {15,20,10,8,12,16,25}, Key : 20Output : 20 found 15 / \ 10 20 / \ / \ 8 12 16 25Table of Content Recursive ApproachIte
3 min read