easy understand java recursive solution


  • 0
    O
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) return 0;
            if(root.left!= null && root.left.left == null && root.left.right == null)
                return root.left.val + sumOfLeftLeaves(root.right);
            else
                return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
        }
    }
    

    We should just focus on one situation: when the left leaf appears, then return the left leaf value, and leave other things to recursion. Besides when the root reference is null pointer, 0 should returned instead.


Log in to reply
 

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