I am looking at LeetCode problem 105. Construct Binary Tree from Preorder and Inorder Traversal:
Given two integer arrays
preorderandinorderwherepreorderis the preorder traversal of a binary tree andinorderis the inorder traversal of the same tree, construct and return the binary tree.# Definition for a binary tree node. class TreeNode(object): def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
Here I read about a nice solution like this:
class Solution:
def buildTree(self, preorder, inorder):
if inorder:
INDEX = inorder.index(preorder.pop(0))
root = TreeNode(inorder[INDEX])
root.left = self.buildTree(preorder, inorder[:INDEX])
root.right = self.buildTree(preorder, inorder[INDEX+1:])
return root
It is clear and useful, but because of the index mechanism, it has a time complexity of O(n²). I want to try to make it more efficient.
I decided to make a map to make it easy to index. Here is what I tried:
class Solution:
def buildTree(self, preorder, inorder):
if not inorder or not preorder:
return None
inorder_map = {value: index for index, value in enumerate(inorder)}
def buildSubTree(preorder, inorder):
if not inorder or not preorder:
return None
root_value = preorder.pop(0)
root = TreeNode(root_value)
root_index = inorder_map[root_value]
root.left = buildSubTree(preorder, inorder[:root_index])
root.right = buildSubTree(preorder, inorder[root_index + 1:])
return root
return buildSubTree(preorder, inorder)
But it returns wrong answers, as for the following input:
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
The expected tree is:
3
/ \
9 20
/ \
15 7
...but my code creates this tree instead:
3
/ \
9 20
/
15
/
7
To reproduce, the following should print True, but it prints False
root = Solution().buildTree([3,9,20,15,7], [9,3,15,20,7])
print(root.right.right is not None) # Should print True
I tried to debug but failed. Where is my mistake?
indexis clearly the wrong answer. I don't think LeetCode guarantees unique values. I used a stack in my solution, rather than recursion. Are you exceeding the time limit?