剑指 Offer 07. 重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
限制:
0 <= 节点个数 <= 5000
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize)
{
if(preorder == NULL || preorderSize == 0 || inorder == NULL || inorderSize == 0)
{
return NULL;
}
struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = *preorder;
root->left = NULL;
root->right = NULL;
for(int i = 0; i < preorderSize; ++i)
{
if(inorder[i] == root->val)
{
int rightval = i + 1;
if(rightval < preorderSize)
{
root->right = buildTree(preorder+rightval, preorderSize - rightval, inorder+rightval, inorderSize - rightval);
}
root->left = buildTree(preorder+1, i, inorder, i);
}
}
return root;
}