【leetcode】剑指 Offer 07. 重建二叉树
//每次找到中间节点 再左右分治 struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){ if(preorderSize==0) return NULL; struct TreeNode *root=(struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val=preorder[0]; int i; for(i=0;i<inorderSize;i++) if(inorder[i]==preorder[0]) break; root->left=buildTree(&preorder[1],i,&inorder[0],i); root->right=buildTree(&preorder[i+1],preorderSize-i-1,&inorder[i+1],preorderSize-i-1); return root; }
//C语言栈迭代算法 struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){ if (preorderSize == 0 || inorderSize == 0) return NULL; struct TreeNode* stack[10000]; int top = -1, i, j = 0; struct TreeNode* root = (struct TreeNode*)calloc(sizeof(struct TreeNode), 1); root->val = preorder[0]; stack[++top] = root; struct TreeNode* temp = root; for (i = 1; i<preorderSize; i++){ struct TreeNode* node = (struct TreeNode*)calloc(sizeof(struct TreeNode), 1); if (top >= 0 && j < inorderSize && stack[top]->val == inorder[j]){ while (i<preorderSize && top >= 0 && j < inorderSize && stack[top]->val == inorder[j]){ node = stack[top--]; j++; } stack[++top] = (struct TreeNode*)calloc(sizeof(struct TreeNode), 1); stack[top]->val = preorder[i]; node->right = stack[top]; } else{ node->val = preorder[i]; temp->left = node; stack[++top] = node; } temp = stack[top]; } return root; }
struct TreeNode* recursion(int* preorder,int preorderSize,int* inorder,int inorderSize,int* preIndex, int* inIndex,int* hash){ if((*preIndex)>=preorderSize || (*inIndex)>=inorderSize) return NULL; struct TreeNode* node = (struct TreeNode*)calloc(sizeof(struct TreeNode),1); node->val=preorder[(*preIndex)]; hash[preorder[(*preIndex)]+20000]++; if(preorder[(*preIndex)]==inorder[(*inIndex)]){ (*inIndex)++; if((*inIndex)<inorderSize && (*preIndex)<preorderSize && hash[inorder[(*inIndex)]+20000]){ (*preIndex)++; (*inIndex)++; return node; } (*preIndex)++; node->right=recursion(preorder,preorderSize,inorder,inorderSize,preIndex,inIndex,hash); return node; } (*preIndex)++; node->left=recursion(preorder,preorderSize,inorder,inorderSize,preIndex,inIndex,hash); if((*inIndex)<inorderSize && hash[inorder[(*inIndex)]+20000]){ (*inIndex)++; return node; } node->right=recursion(preorder,preorderSize,inorder,inorderSize,preIndex,inIndex,hash); return node; } struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){ if (preorderSize==0 || inorderSize==0) return NULL; int preIndex=0, inIndex=0; int hash[40001]={0}; return recursion(preorder,preorderSize,inorder,inorderSize,&preIndex,&inIndex,hash); }