Java recursive solution


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

Log in to reply
 

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