Friday, May 9, 2014

Leetcode (Python): Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

Solution:


We implement the algorithm recursively, for instance given the tree to obtain


That corresponds to the lists:
preorder: A B D E C and inorder: D B E A C

We see that the first element of the preorder corresponds to the root value, A.
Note that by definition:
  • All the elements in the inorder tree previous to this element (A) belong to the left tree and appear in the preorder tree just after the root.
  • All the elements in the inorder tree after this element (A) belong to the right tree and appear in the preorder tree at the end.
# 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, a list of integers
    # @param inorder, a list of integers
    # @return a tree node
    def buildTree(self, preorder, inorder):
        return self.buildTreeRec(preorder, inorder, 0, 0, len(preorder))
        
    def buildTreeRec(self, preorder, inorder, indPre, indIn, element):
        if element==0:
            return None
        solution = TreeNode(preorder[indPre])
        numElementsLeftSubtree = 0;
        for i in range(indIn, indIn+element):
            if inorder[i] == preorder[indPre]:
                break
            numElementsLeftSubtree += 1
        solution.left = self.buildTreeRec(preorder, inorder, indPre+1, 
indIn, numElementsLeftSubtree)
        solution.right = self.buildTreeRec(preorder, inorder, indPre+numElementsLeftSubtree+1,
 indIn+numElementsLeftSubtree+1, element-1-numElementsLeftSubtree)
        return solution

No comments :

Post a Comment