【leetcode】106. 从中序与后序遍历序列构造二叉树
struct TreeNode* buildTree(int* inorder,int inorderSize,int* preorder,int preorderSize){ if(preorderSize==0 || inorderSize==0) return NULL; struct TreeNode** stArr=(struct TreeNode**)calloc(preorderSize,sizeof(struct TreeNode*)); int top=-1, pPst=preorderSize-1, iPst=inorderSize-1, flag=iPst; struct TreeNode* root=(struct TreeNode*)calloc(1,sizeof(struct TreeNode)); struct TreeNode* temp=root; root->val=preorder[pPst--]; stArr[++top]=root; while(pPst>=0 && iPst>=0){ while(top>=0 && stArr[top]->val == inorder[iPst]){ temp=stArr[top--]; iPst--; } struct TreeNode* node=(struct TreeNode*)calloc(1,sizeof(struct TreeNode)); node->val=preorder[pPst--]; stArr[++top]=node; if(flag != iPst) temp->left=node; else temp->right=node; temp=node; flag=iPst; } return root; }