Create trees2.java - #1599
Conversation
Construct Binary Tree from Inorder and Postorder Traversal (trees2.java)Your solution is correct and demonstrates a good understanding of the recursive approach. However, there are significant efficiency concerns:
class Solution {
Map<Integer, Integer> inorderMap;
int postIdx;
public TreeNode buildTree(int[] inorder, int[] postorder) {
inorderMap = new HashMap<>();
postIdx = postorder.length - 1;
for (int i = 0; i < inorder.length; i++) {
inorderMap.put(inorder[i], i);
}
return build(inorder, postorder, 0, inorder.length - 1);
}
private TreeNode build(int[] inorder, int[] postorder, int start, int end) {
if (start > end) return null;
int rootVal = postorder[postIdx--];
int rootIdx = inorderMap.get(rootVal);
TreeNode root = new TreeNode(rootVal);
root.right = build(inorder, postorder, rootIdx + 1, end);
root.left = build(inorder, postorder, start, rootIdx - 1);
return root;
}
}
VERDICT: NEEDS_IMPROVEMENT Sum Root to Leaf NumbersStrengths:
Areas for Improvement:
Suggested refactor: class Solution {
public int sumNumbers(TreeNode root) {
return helper(root, 0);
}
private int helper(TreeNode root, int currNum) {
if (root == null) return 0;
currNum = currNum * 10 + root.val;
if (
VERDICT: PASS |
No description provided.