Java Extremely Simple to understand - Short Code - Recursion


  • 0
    J

    Every time we pass to the left child of a tree, we pass in True. Every time we pass right, we pass in False.

    When it finally gets to a leaf node, the receive a True if it is a left leaf.

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

Log in to reply
 

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