描述
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
分析
经典题,从前序遍历和中序遍历重建二叉树。前序遍历的第一个节点肯定是root,在中序遍历中查找root,可以把中序遍历分为两部分,root前面的是左子树的中序遍历,后面的是右子树的中序遍历。对应地,也可以确定前序遍历左子树和右子树的分界(通过中序遍历左子树的大小),这样递归可解。
时间O(n),空间平均O(logn)。
代码
Python
1 | class Solution(object): |