3. Reconstruction of binary tree
Title Description
Enter the results of the preorder traversal and inorder traversal of a binary tree, and rebuild the binary tree. It is assumed that the results of the input preorder traversal and preorder traversal do not contain duplicate numbers. For example, if the sequence {1,2,4,7,3,5,6,8} and the sequence {4,7,2,1,5,3,8,6} are input, the binary tree will be reconstructed and returned..
Knowledge points
:
Binary tree traversal
Solving problems
The input is the result of pre order traversal and middle order traversal, as shown in the example:
Foreword: 1 2 4 7 3 5 6 8
Medium sequence: 4 7 2 1 5 3 8 6
Find the root node through the pre order and the left and right subtrees through the middle order
The first node in the front order is the root node. Find the location of the root node in the middle order. The substring on the left side of the root node is the left subtree, and the substring on the right side of the root node is the right subtree. Then two sub strings are proposed to construct the sub tree. Until the proposed substring is 0
Code block
/**
* 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) {
if(pre.empty() && vin.empty())return NULL;
int len = pre.size();
TreeNode* root = new TreeNode(pre[0]) ; //The first node of pre is always the root node
int root_id = 0;//Record the subscript of root in the middle order
int leftlen;
int riglen;
for(int i = 0; i<vin.size(); i++){
if(vin[i] == pre[0]){
root_id = i;
break;
}
}
vector<int> lef_t,vin_t,rig_t;
for(int i = 0; i<len; i++){
if(i<root_id)
lef_t.push_back(vin[i]);
else if(i>root_id)
rig_t.push_back(vin[i]);
}
vector<int> lef_son_pre(pre.begin()+1,pre.begin()+root_id+1);
vector<int> left_son_in(vin.begin(),vin.begin()+root_id);
vector<int> right_son_pre(pre.begin()+root_id+1,pre.end());
vector<int> right_son_in(vin.begin()+root_id+1,vin.end());
root->left = reConstructBinaryTree(lef_son_pre,left_son_in);
root->right = reConstructBinaryTree(right_son_pre,right_son_in);
return root;
}
};