Open In App

Sum of Left leaves in Binary Tree using JavaScript

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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));

Output
24

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));

Output
24

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));

Output
24

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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads