Simple recursion ( Java )


  • 0
    R
    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return sumOfLeftLeaves(root, false);
        }
        
        public int sumOfLeftLeaves(TreeNode root, boolean isLeftChild) {
            if(root == null) return 0;
            if(isLeaf(root) && isLeftChild) return root.val;
            
            return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false);
        }
        
        private boolean isLeaf(TreeNode root) {
            return root.left == null && root.right == null;
        }
    }
    

Log in to reply
 

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