思路:
DFS。
Example:
Pre-Order:4 2 1 3 5 6
In-Order:1 2 3 4 5 6
先从Pre-Order中找到的第一个肯定是root,这里是4,然后从In-Order中以4为界,左边是root的左子树的元素,右边是root的右子树的元素,这里1,2,3是root的左子树的元素,5,6是root的右子树的元素,依次类推,再构造root的左子树和右子树,并且让root->left = 构造的左子树rootLeft & root->right = 构造的右子树的rootRight 。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
//Construct Binary Tree from Preorder and Inorder Traversal
template<typename Iter>
TreeNode* build(Iter pBegin, Iter pEnd, Iter iBegin, Iter iEnd) {
if(pBegin == pEnd) return NULL;
if(iBegin == iEnd) return NULL;
int val = *pBegin;
auto iRoot = find(iBegin, iEnd, val);
TreeNode *root = new TreeNode(*iRoot);
int leftSize = iRoot - iBegin;
root->left = build(pBegin+1, pBegin+leftSize+1, iBegin, iRoot);
root->right = build(pBegin+leftSize+1, pEnd, iRoot+1, iEnd);
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
size_t size = inorder.size();
if(size == 0) return NULL;
return build(preorder.begin(), preorder.end(), inorder.begin(), inorder.end());
}
};