4 lines Java with / without global variable, DFS


  • 0

    without global variable

        public int sumOfLeftLeaves(TreeNode root) {
            return helper(root, false);
        }
        public int helper(TreeNode root, boolean left) {
            if (root == null) {return 0;}
            if (left && root.left == null && root.right == null) {return root.val;}
            return helper(root.left, true) + helper(root.right, false);
        }
    

    with global variable

        int sum = 0;
        public int sumOfLeftLeaves(TreeNode root) {
            helper(root, false);
            return sum;
        }
        
        public void helper(TreeNode root, boolean left) {
            if (root == null) {return;}
            if (left && root.left == null && root.right == null) {sum += root.val;}
            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.