Java simple recursive solution


  • 0
    A

    Explanations in the code comments

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            // algorithm: simply recursively adding all left leaves
            int result = 0;
            if (null == root) {
                return 0;
            } else {
                if (isLeafNode(root.left)) {
                    result += root.left.val;
                }
                result += sumOfLeftLeaves(root.left);
                result += sumOfLeftLeaves(root.right);
            }
            return result;
        }
    
        private boolean isLeafNode(TreeNode node) {
            if (null == node) return false;
            else return null == node.left && null == node.right;
        }
    }

Log in to reply
 

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