Adding solution-2#1588
Conversation
Construct Binary Tree from Inorder and Postorder Traversal (W4_2_sum_root_to_leaf.py)It seems there has been a mix-up. The problem you were asked to solve is "Construct Binary Tree from Inorder and Postorder Traversal", but your solution is for "Sum Root to Leaf Numbers". Please double-check the problem statement. For the correct problem, you need to build a binary tree from its inorder and postorder traversal arrays. The key idea is to use the last element in the postorder array as the root, then locate this root in the inorder array to split the array into left and right subtrees. You can then recursively build the left and right subtrees. Here are some tips for solving the correct problem:
VERDICT: NEEDS_IMPROVEMENT Root to Leaf SumYour solution is on the right track and you have correctly implemented the DFS traversal. However, there is a subtle issue with the order of operations. You are checking for leaf node after recursively processing both children. This is inefficient because you are making recursive calls for null children (which immediately return) and then checking the leaf condition. The standard approach is to check for leaf node immediately after updating the current number, and if it is a leaf, add to the result and return without going into children (since they are null). This way, you avoid unnecessary recursive calls for null children. Here is how you can improve your helper function: This change will make your code more efficient by avoiding unnecessary recursive calls for null children. Also, it is more intuitive because you handle the leaf node immediately when you encounter it. Your time and space complexity analysis is correct. Keep up the good work! VERDICT: NEEDS_IMPROVEMENT |
Solution 2 - W4_2_sum_root_to_leaf.py