剑指OFFER 重建二叉树
使用的是递归的算法,不断基于前序遍历的父亲结点把中序遍历数组分成两半.
其状态图,之后再补充
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void reconstruct_recur(TreeNode* &node,vector<int> &pre,vector<int> &vin,int pre_left,int pre_right,int vin_left,int vin_right)
{
if(pre_left>pre_right || vin_left>vin_right)return;
node =(TreeNode*)malloc(sizeof(TreeNode));
node->val = pre[pre_left];
node->left = NULL;
node->right = NULL;
auto vin_it = find(vin.begin()+vin_left,vin.end()+vin_right,pre[pre_left]);
int vin_index = vin_it - vin.begin() - vin_left;//代表着vin从"中间"划分后左边元素的个数
reconstruct_recur(node->left,pre,vin,pre_left+1,pre_left+vin_index,vin_left,vin_left+vin_index-1);//左边
reconstruct_recur(node->right,pre,vin,pre_left+vin_index+1,pre_right,vin_left+vin_index+1,vin_right);//右边
}
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
TreeNode* root = NULL;
reconstruct_recur(root,pre,vin,0,pre.size()-1,0,vin.size()-1);
return root;
}
};