Leetcode 404. Sum of Left Leaves
Given the root of a binary tree, return the sum of all left leaves.
A “leaf” is a node with no children. A “left leaf” is a leaf located on the left subtree of its parent.
To solve this problem, we can use recursion:
Detailed Steps:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int sumOfLeftLeaves(TreeNode root) {
return sumOfLeftLeavesHelper(root, false);
}
private int sumOfLeftLeavesHelper(TreeNode node, boolean isLeft) {
if (node == null) {
return 0;
}
if (node.left == null && node.right == null && isLeft) {
return node.val;
}
return sumOfLeftLeavesHelper(node.left, true) + sumOfLeftLeavesHelper(node.right, false);
}
}
The time complexity of this solution is O(N) where N is the number of nodes in the tree.
The space complexity is O(H) where H is the height of the binary tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?