Skip to content

Instantly share code, notes, and snippets.

@viveksyngh
Created September 29, 2015 06:10
Show Gist options
  • Select an option

  • Save viveksyngh/c7d4af9530c7c17cde54 to your computer and use it in GitHub Desktop.

Select an option

Save viveksyngh/c7d4af9530c7c17cde54 to your computer and use it in GitHub Desktop.
Given preorder and inorder traversal of a tree, construct the binary tree.
__author__ = 'Vivek'
#Given preorder and inorder traversal of a tree, construct the binary tree.
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param preorder : list of integers denoting preorder traversal of tree
# @param inorder : list of integers denoting inorder traversal of tree
# @return the root node in the tree
def buildTree(self, preorder, inorder):
if len(inorder) == 0 and len(preorder) == 0:
return None
else :
val = preorder[0]
root = TreeNode(val)
i = inorder.index(val)
#print i
root.left = self.buildTree(preorder[1 : i + 1], inorder[ : i])
root.right = self.buildTree(preorder[i+1 : ], inorder[i+1 :])
return root
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment