根据中序和前序遍历还原二叉树

思路就是从前序遍历出发,到中序遍历中找到相应的根节点,然后确定左子树和右子树的范围

struct BiNode
{
    int value;
    BiNode *leftchild;
    BiNode *rightchild;
};


class solution
{
public:
     BiNode* BiTree(int *preorder,int *midorder,int length)
    {
        if(length < 0 || preorder == nullptr || midorder == nullptr)
            return nullptr;
        return constructTree(preorder,preorder+length,midorder,midorder+length);
    }
    BiNode* constructTree(int* pre,int* pre_end,int* mid,int* mid_end)
    {
        int rootValue = pre[0];
        BiNode* root = new BiNode();
        root->value = rootValue;
        root->leftchild = nullptr;
        root->rightchild = nullptr;

        if(pre == pre_end) //×ó×ÓÊ÷½áÊø
        {
            if(mid == mid_end && mid == pre)
                return root;
            else
                throw std::exception("Invalid input.")
        }
        int* root_index = mid;

        while( root_index <=mid_end &&*root_index != rootValue)
            root_index++;

        int left_length = root_index - mid;
        int* left_end = pre + left_length;
        if(left_length > 0)
        {
            root->leftchild = constructTree(pre+1,pre_end,mid,root_index-1);
            root->rightchild = constructTree(pre+1,pre_end,root_index+1,mid_end);

        }
        return root;
    }
};

最近开学,都没有什么时间继续学习这方面的东西了,o(╥﹏╥)o

posted @ 2018-09-03 22:41  快乐的打字员~  阅读(143)  评论(0编辑  收藏  举报