运用递归的方法:
首先将前序首元素存为root的根节点
然后利用preorder的首元素找到inorder中根节点的下标
之后创建两个新的数组分别保存preorder和inorder根节点左子树的元素然后就是递归了将左子树元素一个个的链接到根节点的左边
然后清空两个临时的数组(是为右子树做准备)
右子树的创建和刚刚的左子树是一样的
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
typedef struct TreeNode TreeNode;
TreeNode *getNewNode(int n) {
TreeNode *p = (TreeNode *)malloc(sizeof(TreeNode));
p->val = n;
p->left = p->right = NULL;
return p;
}
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
if (preorderSize == 0) return NULL;
int n = preorderSize, pos = 0;
while (inorder[pos] != preorder[0]) pos += 1;
struct TreeNode *root = getNewNode(preorder[0]);
int preArr[3001] = {0}, inArr[3001] = {0}, k1 = 0, k2 = 0;
for (int i = 1; i <= pos; ++i) preArr[k1++] = preorder[i];
for (int i = 0; i < pos; ++i) inArr[k2++] = inorder[i];
root->left = buildTree(preArr, k1, inArr, k2);
memset(preArr, 0, sizeof(preArr));
memset(inArr, 0, sizeof(inArr));
k1 = k2 = 0;
for (int i = pos + 1; i < n; ++i) preArr[k1++] = preorder[i];
for (int i = pos + 1; i < n; ++i) inArr[k2++] = inorder[i];
root->right = buildTree(preArr, k1, inArr, k2);
return root;
}