Prove safety - face questions -07 rebuild binary tree

And enter the result in a preorder traversal of a binary tree in preorder traversal of the binary tree rebuild. Suppose Results preorder traversal order and input of duplicate numbers are free.

For example, given

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

Returns the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

limit:

0 <= the number of nodes <= 5000

Problem-solving ideas

  1. According to a first element to establish root preamble sequence;
  2. The sequence element found in the sequence, the determined left and right subtrees of the root node in order of the sequence;
  3. Determining left and right subtree preamble sequence motif sequence in the preceding;
  4. Establishing left subtree preamble sequence by a left subtree and motif sequence;
  5. Establishing the right subtree of the preamble sequence and the right subtree of the motif sequences.
def buildTree(preorder, inorder):

    if not preorder:
        return None
    loc = inorder.index(preorder[0])
    root = TreeNode(preorder[0])
    root.left = buildTree(preorder[1: loc + 1], inorder[: loc])
    root.right = buildTree(preorder[loc + 1:], inorder[loc + 1:])
    return root

Guess you like

Origin www.cnblogs.com/TuringEmmy/p/12512613.html