73. Construct Binary Tree from Preorder and Inorder Traversal

题目

https://www.lintcode.com/problem/construct-binary-tree-from-preorder-and-inorder-traversal/description?_from=ladder&&fromId=2

实现

  1. preorder 的第一个元素就是根元素
  2. 找到 inorder 根元素的位置
  3. 然后分成两边 divide and conquer

代码

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None


class Solution:
    """
    @param preorder : A list of integers that preorder traversal of a tree
    @param inorder : A list of integers that inorder traversal of a tree
    @return : Root of a tree
    """

    def buildTree(self, preorder, inorder):
        if len(inorder) == 0:
            return None

        root = TreeNode(preorder[0])
        rootPos = inorder.index(preorder[0])

        root.left = self.buildTree(preorder[1:rootPos + 1], inorder[:rootPos])
        root.right = self.buildTree(preorder[rootPos + 1:], inorder[rootPos + 1:])

        return root

你可能感兴趣的:(73. Construct Binary Tree from Preorder and Inorder Traversal)