Created
September 29, 2015 06:09
-
-
Save viveksyngh/c0984ce8b43d89035382 to your computer and use it in GitHub Desktop.
Given inorder and postorder traversal of a tree, construct the binary tree.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| __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