Java 8ms self explanatory solution (DFS)

  • 1
            // for explanatory
    	private final boolean LEFT = true;
    	private final boolean RIGHT = false;
    	public int sumOfLeftLeaves(TreeNode root) {
    		if (root == null)
    			return 0;// root is not leaf
    		return helper(root.left, LEFT) + helper(root.right, RIGHT);
    	private int helper(TreeNode cur, boolean branch) {// branch can be replace with 'isLeft'
    		if (cur == null)
    			return 0;
    		if (branch == LEFT && isLeaf(cur))
    			return cur.val;// add value only when it's left. If right,ignored.
    		return helper(cur.left, LEFT) + helper(cur.right, RIGHT);
            private boolean isLeaf(TreeNode root) { // note: NullPointerException
    		return root.left == null && root.right == null;

    may be a bit longer but easier to explain and read.

Log in to reply

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