Recursive java solution with param parent node


  • 0
    L
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
            return helper(root, root);
        }
        
        private int helper(TreeNode root, TreeNode parent) {
            // base case, leaf node
            if (root.left == null && root.right == null) {
                return parent.left == root ? root.val : 0;
            }
            
            int sum = 0;
            if (root.left != null) sum += helper(root.left, root);
            if (root.right != null) sum += helper(root.right, root);
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.