Leetcode - Construct Binary Tree from Inorder and Postorder Traversal (Python)

preview_player
Показать описание
July 2020 Leetcode Challenge
Leetcode - Construct Binary Tree from Inorder and Postorder Traversal
Рекомендации по теме
Комментарии
Автор

aye yai yai....i hate these problems

thanks tim!

EDIT: Also, I think it was really great when you were explaining the recusrive call, you left the base condition to be filled out later, but just created the body of the helper first. It helps me out too because I pause every few seconds to try to see if I can code out what you do! Thanks man!

janmichaelaustria
Автор

Best and the easiest solution out there. Thanks!

siddharthsingh
Автор

I have a question on it. Why I got an error message with "if inorder ==None or postorder == None"?

lucylu
Автор

how do you come up with these types of solutions ? is there any book which even I can reference?

siddharthsingh
Автор

Here is what was my first attempt at an iterative version, that ended up timing out on large input size! Can you guess the time complexity? xD

def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:

head = TreeNode(postorder[-1])
for x in reversed(postorder[:-1]):
curr = head
y = 0
while True:
if inorder[y] == curr.val:
if curr.right is None:
curr.right = TreeNode(x)
break
else:
curr = curr.right
y = 0
elif inorder[y] == x:
if curr.left is None:
curr.left = TreeNode(x)
break
else:
curr = curr.left
y = 0
else:
y += 1
return head

scullyy
Автор

Shouldn't the Space Complexity be O(N) as we are creating a mapper?

jadhavswapnil
Автор

Best solution I have seen on this problem.. Thanks

sharifmansuri
Автор

Hello why root.right is before root.left?

Iamnoone
Автор

Here is a different approach that uses a more intuitive recursion:

miteshkumar