无聊的刷题笔记

重建二叉树

剑指Offer 7

中序前序重建二叉树

通过中序的val分割左右子树,递归下去。

/**
* 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.size()==0) {
return nullptr;
}
int mid = pre[0];
vector<int> leftPre, leftVin;
vector<int> rightPre, rightVin;
int left=0;
for (int i=0;i<vin.size();i++) {
if (vin[i]==mid) {
left = i;
break;
}
}
for (int i=0;i<left;i++){
leftPre.push_back(pre[i+1]);
leftVin.push_back(vin[i]);
}
for (int i=left+1;i<pre.size();i++){
rightPre.push_back(pre[i]);
rightVin.push_back(vin[i]);
}
TreeNode* node = new TreeNode(mid);
node->left = reConstructBinaryTree(leftPre, leftVin);
node->right = reConstructBinaryTree(rightPre, rightVin);
return node;
}
};