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.
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.
Sum of Left leaves in Binary Tree using JavaScript
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:
Table of Content
- Recursive Method
- Iterative Method Using Stack
- BFS with Queue