"Left Lean" Loop with Recursion (Java)


  • 0

    The idea is: for each "left lean" path, try to find its "end leaf" with a while loop. When passing by each node, gather the value from the node's right sub-tree.

        public int sumOfLeftLeaves(TreeNode root) {
            if (root == null) return 0;
            TreeNode curr = root;
            int sum = 0;
            while (true) {
                sum += sumOfLeftLeaves(curr.right);
                curr = curr.left;
                if (curr == null) break;
                if (curr.left == null && curr.right == null) {
                    sum += curr.val;
                    break;
                }
            }
    
            return sum;
        }
    

Log in to reply
 

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