题目
已知:
前序 1,2,4,7,3,5,6,8
中序 4,7,2,1,5,3,8,6
要求:
重新构建一颗二叉树
解答
因为前序的第一个就是根节点,所以先找到根节点在中序中的位置
求出左子树的长度,确定左子树在前序和中序中的范围,以及右子树在前序和中序中的范围
求出两个序列中,左子树的范围和右子树的范围
class Solution {
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
return pre_order(0, vin.size() - 1, 0, vin.size() - 1, pre, vin);
}
TreeNode *pre_order(int leftpre, int rightpre, int leftin, int rightin, vector<int> &pre, vector<int> &in) {
if (leftpre > rightpre || leftin > rightin)
return NULL;
TreeNode *root = new TreeNode(pre[leftpre]);
int rootin = leftin;
while (rootin <= rightin && pre[leftpre] != in[rootin])
rootin++;
int left = rootin - leftin;
root->left = pre_order(leftpre + 1, leftpre + left, leftin, rootin - 1, pre, in);
root->right = pre_order(leftpre + left + 1, rightpre, rootin + 1, rightin, pre, in);
return root;
}
};
参考:
重建二叉树