Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

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