7 lines Recursive solution


  • 0
    C
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root==null) return 0;
            return sum(root,false);
        }
        public int sum(TreeNode root, boolean left){
            if(root==null) return 0;
            else if(left && root.left==null && root.right==null) return root.val;
            else return sum(root.left, true)+sum(root.right, false);
        }
    }

Log in to reply
 

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