Most Straightforward Recursive Java Solution.


  • 1
    Z

    I came up with a more straightforward way to solve this problem, a little bit like the recursive way above. Instead of do it in the original function, I traverse the tree in inOrder sequence but with the tree side information.

    int sum;
    public int sumOfLeftLeaves(TreeNode root) {
        sum = 0;
        inOrder(root, false); // false means the next node is not in left side.
        
        return sum;
    }
    
    private void inOrder(TreeNode root, boolean left) {
        if (root == null) {
            return;
        }
        
        inOrder(root.left, true); // true means the next node is in left side.
        if (root.left == null && root.right == null && left) { //only left leaves would be added to sum.
            sum += root.val;
        }
        inOrder(root.right, false);
    }

  • 0
    C

    @ZhuEason Now I realized how unnecessarily complicated my recursion is LOL


Log in to reply
 

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