解题思路:
前序遍历preorder中,第一个即为根节点,然后找到中序遍历inorder中对应的节点,则inorder中该节点之前的值均在根节点的左子树上,该节点后面的值都在根节点的右子树上,所以可以使用递归构建二叉树,分别对其左子树的节点、右子树的节点构建数。
/**
* 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 conTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
TreeNode* conTree(vector<int>& preorder, int pl, int pr, vector<int>& inorder, int il, int ir){
if(pl > pr || il > ir)
return NULL;
TreeNode* root = new TreeNode(preorder[pl]);
for(int i = il; i <= ir; i++){
if(preorde