Java recursive solution, easy to understand


  • 0
    Y
        public int sumOfLeftLeaves(TreeNode root) {
            if(root == null) {
                return 0;
            }
            int[] sum = new int[]{0};
            TreeNode[] prev = new TreeNode[1];
        // previous node is used below to check if current node is its left child
            getSum(root, sum, prev);
            return sum[0];
            
        }
        private void getSum(TreeNode root, int[] sum, TreeNode[] prev) {
            if(root == null) {
                return;
            }
            if(root.left == null && root.right == null && prev[0] != null && prev[0].left == root) {
                sum[0] += root.val;
            }
            prev[0] = root; // update previous node
            getSum(root.left, sum, prev);
            getSum(root.right, sum, prev);
            
        }
    

Log in to reply
 

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