题解
实际上是一个模拟题,详细的看一下根据前序序列和中序序列建立二叉树的sua
代码:
class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { vector<int> pre_left; vector<int> pre_right; vector<int> vin_left; vector<int> vin_right; if(pre.size() == 0 || vin.size() == 0) { return nullptr; } int head = pre[0]; int split_index = -1; bool flag = 0; for(int i = 0; i < vin.size(); i++) { if(vin[i] == head) { flag = 1; split_index = i; continue; } else if(flag == 0) { vin_left.push_back(vin[i]); } else if(flag == 1) { vin_right.push_back(vin[i]); } } for(int i = 1 ; i <= vin_left.size(); i++) { pre_left.push_back(pre[i]); } for(int i = vin_left.size() + 1; i < pre.size(); i++) { pre_right.push_back(pre[i]); } TreeNode* root = new TreeNode(head); root->left = reConstructBinaryTree(pre_left, vin_left); root->right = reConstructBinaryTree(pre_right, vin_right); return root; } };