105. Construct Binary Tree from Preorder and Inorder Traversal

problem description

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

algorithm thought

前序遍历和中序遍历转二叉树,首先利用前序遍历第一个值就是当前根节点的性质。找到根节点,只有去中序遍历中找到根节点对应的位置,位置左边就是左子树右边是右子树。然后对于左右子树,得到他们的大小,去前序遍历中找到他们对应的位置。然后对于左右子树,递归解决。

code

algorithm analysis

每次在中序遍历中找到根节点的位置,一般情况下需要O(n)时间。那总时间可以表达为T(n)=2T(n/2)+O(n),这个表达式用主定理分析可知为T(n)=O(nlgn)

Last updated