sum-of-left-leaves

package us.inest.app.dcp.recursion;

import us.inest.app.dcp.tree.TreeNode;

public class SumOfLeftLeaves {

public static int sumOfLeftLeaves(TreeNode root) {

// base case

if (root == null) {

return 0;

}

// left child is a leaf node

if (root.left != null && root.left.left == null && root.left.right == null) {

return root.left.data + sumOfLeftLeaves(root.right);

}

return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);

}

}

About Hieu Nguyen

I am a Senior member of technical staff (Oracle, eBay, Microsoft) and a founder of iNest, LLC (an IoT company)
This entry was posted in recursion. Bookmark the permalink.