Java Super Easy Understanding Recursive Method


  • 0
    Y

    The idea is to add a helper function and pass one more parameter representing as left node or not

    public class Solution {
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) return 0;
            return helper(root.left,true) + helper(root.right,false);
        }
        private int helper(TreeNode root, boolean leftNode){   // if leftNode, pass true, if not, pass false
            if(root == null) return 0;
            if(root.left == null && root.right == null && leftNode) return root.val;
            return helper(root.left,true) + helper(root.right,false);
        }
    }
    

Log in to reply
 

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