Rebuild binary tree
Scene reproduction
When tried to solve this question, I first simulate the process of rebuild binary tree by hand, and I found that the root could be determined from the preorder traversal, and then separate the inorder traversal into two part recursively, then found the children in the two parts. However, I didn’t do well in simplifying the recursive process, which led to my confusing into the condition to return. What’s more, I didn’t discover that the preorder sequence should also be separated in each recursive time, which made my result wrong.
After referring to the sample code posted by a net friend, I clear the way to solve the question better.
Solution
The process is recurssive, but we should take the easiest case at the beginning, then replace the case to the function.
The easiest case is that, after all the children is determined, we need to add them to the root. The root is the first element of the preorder sequence.
At first, we make a TreeNode whose value is pre[0], then we find the value in the vin[i2,j2] vector, after finding its position, we separate the vin vector into two part: left and right, and then, solve left and right sub question. We should notice that, when the vin vector is separated to left:vin[i2,i-1] and right: vin[i+1,j2] ,the pre[i1,j1] should be separated into left: pre[i1, i1+i-i2] and right right: pre[i1+i-i2,j2], so that the program can choose the correct root of left and right from their pre sequence.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> pre1, vin1;
TreeNode* find(int i1, int j1, int i2, int j2){
// find the root
if(i1>j1||i2>j2){
return NULL;
}
int rootval = pre1[i1];
TreeNode* root = new TreeNode(rootval);
// error: write < instead of <=
for(int i = i2; i<=j2; i++){
if(vin1[i] == rootval){
// ? Why do we need to -i2 ?
root->left = find(i1+1,i1+i-i2,i2,i-1);
root->right = find(i1+i-i2+1,j1,i+1,j2);
}
}
return root;
}
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
// initial
int n = vin.size();
pre1 = pre;
vin1 = vin;
TreeNode* res = find(0,n-1,0,n-1);
return res;
}
};