本文最后更新于:2020年6月28日 下午

题目描述:

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

实现如下:

//前序中序、后序中序都可以重建二叉树,但前序后序不可以,因为只有中序可以区分左子树与右子树
/*
pre:{1,2,4,7,3,5,6,8}
vin:{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, vector<int> vin)
    {
	    //判断异常情况:前序为空或后序为空或两者个数不同
        if (pre.size() == 0 || vin.size() == 0 || pre.size() != vin.size()) 
	        return NULL;
        else //调用递归函数
	        return ConstructBinaryTree(pre.begin(), vin.begin(), pre.size());
    }
 
    TreeNode* ConstructBinaryTree(vector<int>::iterator itp, vector<int>::iterator itv, int n)
    {
        TreeNode *s = NULL;
        if (n > 0)
        {
            s = new TreeNode(*itp);
            //在中序序列中寻找根结点的对应下标
            int index = FindIndex(itv, n, *itp);
            if (index == -1) exit(-1);//未找到数字,序列错误
            //缩小节点的范围,仅限s的左子树,注意下标和个数的变化
            s->left = ConstructBinaryTree(itp + 1, itv, index);
            //缩小节点的范围,仅限s的右子树
            s->right = ConstructBinaryTree(itp + index + 1, itv + index + 1, n - index - 1);
        }
        return s;
    }
    int FindIndex(vector<int>::iterator itv, int n, int x)
    {
        for (int i = 0; i < n; ++i, ++itv)
        {
            if (*itv == x) return i;
        }
        return -1;//未找到返回-1
    }
};