//最大的收获分析这里面的边界问题
中序,后序重构二叉树
struct TreeNode* buildTree(int* inorder, int inorderSize, int* postorder, int postorderSize) {
if (postorderSize == 0)
return NULL;
struct TreeNode *p = (struct TreeNode*)malloc(sizeof(struct TreeNode));
p->val = postorder[postorderSize-1];
int pos;
for (int i = 0; i < inorderSize; i++)
{
if (inorder[i] == postorder[postorderSize - 1])
{
pos = i;
break;
}
}
p->left = buildTree(inorder,pos,postorder,pos);
p->right = buildTree(inorder + pos + 1, inorderSize - pos -1,postorder + pos,postorderSize - pos - 1);
return p;
}
前序遍历和中序遍历重构二叉树
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder,
int inorderSize) {
if (preorderSize == 0 )
return NULL;
struct TreeNode* p = (struct TreeNode*)malloc(sizeof(struct TreeNode));
p->val = preorder[0];
int pos = 0;
for (int i = 0; i < preorderSize; i++) {
if (preorder[0] == inorder[i]) {
pos = i;
break;
}
}
p->left = buildTree(preorder+1,pos,inorder,pos);
p->right = buildTree(preorder+pos+1,preorderSize-pos-1,inorder+pos+1,inorder-pos-1);
return p;
}
这位其中这递归的边界分析如图:
这里要先找出特殊的值,然后逐渐找出递归函数俩边的边界