给定节点数为 n 的二叉树的前序遍历和中序遍历结果,请重建出该二叉树并返回它的头结点。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建出如下图所示。
递归解法
利用递归不断缩小问题的规模,通过下标进行控制。
/**
* 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, int pre_start, int pre_end, vector<int>& vin, int vin_start, int vin_end)
{
// 递归终止条件
if(pre_start > pre_end || vin_start > vin_end)
return nullptr;
// 根结点
TreeNode* root = new TreeNode(pre[pre_start]);
// 在vin中找到对应数字的下标
for(int i = vin_start; i <= vin_end; ++i)
{
if(pre[pre_start] == vin[i])
{
// 找到了
// [vin_start, i-1] i [i+1, vin_end]
root->left = _reConstructBinaryTree(pre, pre_start+1, i-vin_start+pre_start, vin, vin_start, i-1);
root->right = _reConstructBinaryTree(pre, i-vin_start+pre_start+1, pre_end, vin, i+1, vin_end);
break;
}
}
return root;
}
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
if(pre.size() == 0 || vin.size() == 0 || pre.size() != vin.size())
return nullptr;
TreeNode* root = nullptr;
root = _reConstructBinaryTree(pre, 0, pre.size()-1, vin, 0, vin.size()-1);
return root;
}
};