Accepted Java solution using Recursion, simple, easy to understand

  • 5

    Use a helper recursion function that specifies if the node is left node or right node.

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            return sumOfLeftLeavesHelper(root, false);
        public int sumOfLeftLeavesHelper(TreeNode root, boolean b) {
            if (root == null) return 0;
            if (root.left == null && root.right == null) {
                if (b) 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.