java solution with explaination


  • 0
    /**
     * 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) {
            // base case
            if(root == null) return 0;
            // if it's leaf, return its value
            if(root.left == null && root.right == null) return 0;
            int left = 0, right = 0;
            // check to see if right node is leaf. If it is not, traverse.
            if(root.right != null && (root.right.left != null || root.right.right != null)) right = sumOfLeftLeaves(root.right);
            if(root.left != null && (root.left.left != null || root.left.right != null)) left = sumOfLeftLeaves(root.left);
            else if(root.left != null && root.left.left == null && root.left.right == null) left = root.left.val;
            return left + right;
        }
    }
    

Log in to reply
 

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