一开始想用两重循环,外循环顺序遍历先序序列,内循环比较中序序列的位置来判断这个节点的左右儿子节点是谁。但是感觉写起来比较麻烦,写到一半卡住了。也想过用递归、或者用堆栈或队列等线性结构辅助,不过也没有具体的实现办法,最后参考了讨论区最高赞的思路,其实相当于又用C++把他的Java代码重新写了一遍。
递归的思路是:找到目前这个子树里的根节点(就是先序序列的第一个),然后把他的左右子树的先序和中序序列标号范围找到:左子树:先序序列,起始标号,终止标号;中序序列,起始标号,终止标号;右子树同理。返回左右子树的根节点指针给原来树的左右指针即可。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
TreeNode* root = reConstructBT(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
return root;
}
private:
TreeNode* reConstructBT(vector<int> pre, int startPre, int endPre, vector<int>vin, int startVin, int endVin){
if(startPre>endPre || startVin>endVin){
return NULL;
}
//TreeNode* root(pre[startPre]) = (TreeNode*)malloc(sizeof(struct TreeNode));
TreeNode* root = (TreeNode*)malloc(sizeof(struct TreeNode));
root->val = pre[startPre];
//root(pre[startPre]);
for(int i=startVin; i<=endVin; i++){
if(vin[i] == pre[startPre]){
root->left = reConstructBT(pre, startPre+1, startPre+i-startVin, vin, startVin, i-1);
root->right = reConstructBT(pre, startPre+1+i-startVin, endPre, vin, i+1, endVin);
break;
}
}
return root;
}
};
19.10.25:
重写这道题,感觉简单了很多。tips:先分别判断左右子树存不存在,再决定要不要递归调用。
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size()==0 || vin.size()==0 || pre.size()!=vin.size()) return nullptr;
int n = pre.size();
return reConstructCore(pre, 0, n-1, vin, 0, n-1);
}
private:
TreeNode* reConstructCore(vector<int>& pre, int preStart, int preEnd, vector<int>& vin, int vinStart, int vinEnd)
{
TreeNode* pRoot = new TreeNode(pre[preStart]);
int index = vinStart;
while(pRoot->val != vin[index] && index<=vinEnd) {
index++;
}
int lenLeftTree = index - vinStart;
//if(preStart<preEnd && vinStart<vinEnd && lenLeftTree>0) //递归条件欠考虑
if(index > vinStart) {
pRoot->left = reConstructCore(pre, preStart+1, preStart+lenLeftTree, vin, vinStart, index-1);
}
if(index < vinEnd) {
pRoot->right = reConstructCore(pre, preStart+lenLeftTree+1, preEnd, vin, index+1, vinEnd);
}
return pRoot;
}
};
20.5.2
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
return buildTreeCore(preorder, inorder, 0, n-1, 0, n-1);
}
TreeNode* buildTreeCore(vector<int>& preorder, vector<int>& inorder, int p_start, int p_end, int i_start, int i_end) {
if(p_start > p_end || i_start > i_end) return nullptr;
TreeNode* root = new TreeNode(preorder[p_start]);
int i;
for(i = i_start; i <= i_end; i++) {
if(inorder[i] == preorder[p_start]) break;
}
root->left = buildTreeCore(preorder, inorder, p_start+1, p_start+(i-i_start), i_start, i-1);
root->right = buildTreeCore(preorder, inorder, p_start+(i-i_start)+1, p_end, i+1, i_end);
return root;
}
};