Problem
Given a binary tree, find the sum of all the nodes which are left as well as leaves nodes.
Examples
Example 1:
graph TD 3 --- 9:::GreenNode & 20 20 --- A[15]:::GreenNode & B[7] classDef GreenNode fill:#0000ff
Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
Example 2:
Input: root = [1]
Output: 0
Solution
Method 1 - Inorder Traversal
Approach: Approach is quite simple:
- Do the inorder traversal
- check if node if the left child and leaf node.
- If yes then add it to the sum.
See the code for more understanding.
Code
Java
public static void leftSum(Node root, Node parent) {
if (root == null) {
return 0;
}
// if left node is present and is a leaf
if (root.left != null && root.left.left == null && root.left.right == null) {
return root.left.val + sumOfLeftLeaves(root.right);
}
return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
}