- 前序和中序确定二叉树
- 前序数组的第一项为根节点;
- 根据前序数组的第一项确定中序数组的分割点,分为左中序数组和右中序数组;
- 根据左中序数组的大小,将前序数组分为左前序数组和右中序数组;
- 左节点由左前序数组和左中序数组确定;
- 右节点由右前序数组和右中序数组确定。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
TreeNode* traversal(vector<int>& pre, vector<int>& vin) {
if (pre.size() == 0) return NULL;
int rootValue = pre[0];
TreeNode* root = new TreeNode(rootValue);
if (pre.size() == 1) return root;
int splitIndex;
for (splitIndex = 0; splitIndex < vin.size(); splitIndex++) {
if (vin[splitIndex] == rootValue) break;
}
vector<int> leftVin(vin.begin(), vin.begin() + splitIndex);
vector<int> rightVin(vin.begin() + splitIndex + 1, vin.end());
vector<int> leftPre(pre.begin() + 1, pre.begin() + leftVin.size() + 1);
vector<int> rightPre(pre.begin() + leftVin.size() + 1, pre.end());
root->left = traversal(leftPre, leftVin);
root->right = traversal(rightPre, rightVin);
return root;
}
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if (pre.size() == 0 || vin.size() == 0) return NULL;
return traversal(pre, vin);
}
};