Easy solution with wrapper class and preorder traversal


  • 0
    A

    I used a wrapper class, which enabled me to pass int as a reference.

    public class Solution {
        private class Result {
            private int value;
            private Result() {
                this.value = 0;
            }
        }
        
        public int sumOfLeftLeaves(TreeNode root) {
            Result res = new Result();
            sumOfLeftLeavesHelper(root, res);
            return res.value;
        }
        
        private void sumOfLeftLeavesHelper(TreeNode root, Result sum) {
            if (root != null) {
                if (root.left != null && root.left.left == null && root.left.right == null) {
                    sum.value += root.left.val;
                }
                sumOfLeftLeavesHelper(root.left, sum);
                sumOfLeftLeavesHelper(root.right, sum);
            }
        }
    }
    

Log in to reply
 

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