Sum of Left Leaves - Tree - Easy - LeetCode
💻 coding

Sum of Left Leaves - Tree - Easy - LeetCode

1 min read 149 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to calculate the sum of all left leaves in a binary tree.
  • 2In the provided example, the left leaves are 9 and 15, resulting in a sum of 24.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to calculate the sum of all left leaves in a binary tree."

Sum of Left Leaves - Tree - Easy - LeetCode

Find the sum of all left leaves in a given binary tree.

Example:

3 / \ 9 20 / \ 15 7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 public int SumOfLeftLeaves(TreeNode root) {
 int res = Helper(root,false);
 return res;
 }
 
 private int Helper(TreeNode root, bool isLeft){
 int sum = 0;
 if(root == null){
 return sum;
 }
 
 if(root.left==null && root.right==null && isLeft){
 sum += root.val;
 }
 
 sum += Helper(root.left, true);
 sum += Helper(root.right, false);
 return sum;
 }
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 6 October 2020 · 1 min read · 149 words

Part of AskGif Blog · coding

You might also like