/
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode left;
* struct TreeNode right;
* };
*/
struct TreeNode bulid(int preorder, int pStart, int pEnd, int* inorder, int iStart, int inorder_size){
if(pStart > pEnd)
return NULL;
//创建二叉树,并建立根节点
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = preorder[pStart];
//找到中序遍历中根节点的位置下标
int index = iStart;
for(index; index < inorder_size; index++){
if(preorder[pStart] == inorder[index])
break;
}
//左子树的节点数为:
int numsOfLeft = index - iStart;
//递归创建二叉树
root->left = bulid(preorder, pStart + 1, pStart + numsOfLeft, inorder, iStart, inorder_size);
root->right = bulid(preorder, pStart + numsOfLeft + 1, pEnd, inorder, index + 1, inorder_size);
return root;
}
struct TreeNode buildTree(int preorder, int preorder_size, int* inorder, int inorder_size) {
return bulid(preorder, 0, preorder_size - 1, inorder, 0, inorder_size);
}