就是在两种序列中,找到根节点与左右子树,之后就是递归了。
/**
* 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 {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* build(vector<int>& preorder, int startPre, int endPre, vector<int>& inorder, int startIn, int endIn){
if(startPre>endPre || startIn>endIn) return nullptr;
int rootVal = preorder[startPre];
TreeNode* root = new TreeNode(rootVal);
if(startPre==endPre) return root;
int rootIn = startIn;
while(rootIn<=endIn && inorder[rootIn]!=rootVal)
++rootIn;
int lenLeft = rootIn - startIn;
root->left = build(preorder,startPre+1,startPre+lenLeft,inorder,startIn,rootIn-1);
root->right = build(preorder,startPre+lenLeft+1,endPre,inorder,rootIn+1,endIn);
return root;
}
};