前序中序遍历构造二叉树

思路
- 在前序中找根结点
- 根据根结点 + 中序,分成左右两棵子树
- 根据子树长度,把前序分成左右两颗子树
- 递归处理子树
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){assert(preorderSize == inorderSize);if (preorderSize == 0){return NULL;}int rootValue = preorder[0];int rindex = -1;for (int i = 0; i < inorderSize; i++){if (inorder[i] == rootValue){rindex = i;}}assert(rindex != -1);struct TreeNode* root = (struct TreeNode *)malloc(sizeof(struct TreeNode));root->val=rootValue;root->left = buildTree(preorder+1,rindex,inorder,rindex);root->right = buildTree(preorder+1+rindex,preorderSize-1-rindex,inorder+rindex+1,inorderSize-rindex-1);return root;
}