Binary Tree Left Leaves Sum: Algorithm and JavaScript Implementation
Binary Tree Left Leaves Sum: Algorithm and JavaScript Implementation
Problem:
Given a binary tree, calculate the sum of all left leaves.
Example:
Input:
+
1
/ \
2 3
Output: 6
Explanation:
Node 1's value is 1, and its two child nodes have values 2 and 3, so the total sum is 6.
Algorithm:
- Base Case: If the root is null, return 0.
- Left Leaf Check: If the current node has a left child, and the left child is a leaf node (has no children), add the left child's value to the sum.
- Recursive Traversal: Recursively call the function for the left and right subtrees.
- Return Sum: Return the total sum calculated.
JavaScript Implementation:
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var sumOfLeftLeaves = function(root) {
if(!root) return 0;
let res = 0;
if(root.left && !root.left.left && !root.left.right){
res += root.left.val;
}else{
res += sumOfLeftLeaves(root.left);
}
res += sumOfLeftLeaves(root.right);
return res;
};
This code uses recursion to traverse the tree and identifies left leaves based on the conditions root.left and !root.left.left && !root.left.right. It efficiently calculates the sum of all left leaves in the binary tree.
AI 优化版
原文地址:https://www.cveoy.top/t/topic/lg4x 著作权归作者所有。请勿转载和采集!