Java recursive solution, easy to understand

  • 1

    I use a bool value to label the left leaf

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return dfs(root, false);
        int dfs(TreeNode root, boolean left) {
            if(root==null) return 0;
            if(left && root.left==null && root.right==null) {
                return root.val;
            return dfs(root.left, true) + dfs(root.right, false);

Log in to reply

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