Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7
  

My code:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
   def buildTree(self, preorder, inorder):
       """
       :type preorder: List[int]
       :type inorder: List[int]
       :rtype: TreeNode
       """
       return self.tree(deque(preorder), inorder)
   def tree(self,preorder, inorder):
       if not inorder:
           return None
       root_val=preorder.popleft()
       root=TreeNode(root_val)
       index=inorder.index(root_val)
       root.left=self.tree(preorder,inorder[:index])
       root.right=self.tree(preorder,inorder[index+1:])
       return root
       

Solution: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/