java DFS with time O(n) space O(1)


  • 0
    E
    public int sumOfLeftLeaves(TreeNode root) {
            // sanity check
            if (root == null) {
                return 0;
            }
            int[] sum = new int[1];
            helper(root, root, sum);
            return sum[0];
        }
        
        private void helper(TreeNode root, TreeNode parent, int[] sum) {
            // base case
            if (root == null) {
                return;
            }
            // recursive rule
            if (root.left == null && root.right == null && parent.left == root) {
                sum[0] += root.val;
                return;
            }
            helper(root.left, root, sum);
            helper(root.right, root, sum);
        }
    

  • 0
    J

    @eric0331
    I try to run this code, but it can catch the last left node's value, but can't add(sum)


  • 1
    E

    @juilacoco
    What is the data type for sum in your code. If you are using int as the data type, sum cannot be added. Because int is primitive type and it will be stored in stack. So the sum will be deleted when the recursion is done. You should use int array instead. Is this the problem?


Log in to reply
 

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