[Java] easy to understand, Recursive

  • 0

    I am going to propose a recursive solution.
    The base case is that we reach any leaf node and return the root's value if the node is a left leaf node.
    The recursion rule is that we need to add the return values of the recursion function of the left subtree and right subtree and then report the result to the parent.
    In implementation: we can use a boolean variable in recursion function to identify if the node is a left child or not.

        public int sumOfLeftLeaves(TreeNode root) {
            return root == null ? 0 : helper (root, false); 
        public int helper(TreeNode root, boolean isLeft) {
            if (root.left == null && root.right == null)    return isLeft ? root.val : 0;
            if (root.left != null && root.right != null)    return helper(root.left, true) + helper(root.right, false);
            return root.left != null ? helper(root.left, true) : helper(root.right, false);

Log in to reply

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