根据二叉树的前序中序遍历序列重建二叉树

来源:互联网 发布:西部世界什么意思 知乎 编辑:程序博客网 时间:2024/05/18 19:40
  • 题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树,假设输入的前序中序遍历结果中不含重复的数字,例如输入前序遍历序列“12473568”,和中序遍历序列“47215386”重建二叉树并输出他的头节点。
    二叉树的节点定义如下
typedef struct BinaryTreeNode{    BinaryTreeNode(char value)    :_value(value)    , _pLeft(NULL)    , _pRight(NULL)    {}    char _value;    BinaryTreeNode *_pLeft;    BinaryTreeNode *_pRight;}BinaryTreeNode;
  • 思路解析
    在二叉树的前序遍历序列中,第一个数值总是二叉树根结点的值,在中序遍历序列中,根结点的值在序列的中间,左子树节点的值位于根节点的值的左边,右子树的节点的值位于根结点的值的右边。
    所以上述序列还原的二叉树如下图所示
    这里写图片描述
    实现代码:
BinaryTreeNode *ConstructCore(char *preStart, char *preEnd, char *inStart, char *inEnd);BinaryTreeNode *Construct(char *preStart, char *inStart, int length){    if (NULL == preStart || NULL == inStart || length <= 0)        return NULL;    return ConstructCore(preStart,preStart + length - 1,inStart,inStart + length - 1);}BinaryTreeNode *ConstructCore(char *preStart, char *preEnd, char *inStart, char *inEnd){    char rootvalue = preStart[0];//前序遍历的第一个节点是树的根    BinaryTreeNode * root = new BinaryTreeNode(rootvalue);    if (preStart == preEnd)    {        if (inStart == inEnd && *inStart == rootvalue)            return root;        else        {            cout << "输入的序列有误" << endl;            return NULL;        }    }    //在中序遍历序列中寻找根所在的位置    char *inRoot = inStart;    while (inRoot <= inEnd && *inRoot != rootvalue)        ++inRoot;    if (inRoot == inEnd && *inRoot != rootvalue)    {        cout << "输入的序列有误" << endl;        return NULL;    }    int leftsize = inRoot - inStart;    int rightsize = inEnd - inRoot;    if (leftsize > 0)    {        root->_pLeft = ConstructCore(preStart + 1, preStart + leftsize, inStart, inRoot - 1);    }    if (rightsize > 0)    {        root->_pRight = ConstructCore(preStart + leftsize + 1,preEnd,inRoot + 1,inEnd);    }    return root;}
  • 测试用例
void FunTest(){    //普通二叉树    char *preorder = "12473568";    char *inorder = "47215386";    BinaryTreeNode * root = Construct(preorder, inorder,8);    //特殊二叉树(左右单支,只有一个根)    char *preorder1 = "124";    char *inorder1 = "421";    BinaryTreeNode * root1 = Construct(preorder1, inorder1, 3);    char *preorder2 = "124";    char *inorder2 = "124";    BinaryTreeNode * root2 = Construct(preorder2, inorder2, 3);    char *preorder3 = "1";    char *inorder3 = "1";    BinaryTreeNode * root3 = Construct(preorder3, inorder3, 1);    //特殊测试(根为空//前序遍历序列与中序遍历序列不匹配)    char *preorder4 = "1247";    char *inorder4 = "421";    BinaryTreeNode * root4 = Construct(preorder4, inorder4, 4);    BinaryTreeNode * root5 = Construct(NULL, NULL, 0);}

完整代码请戳:
https://coding.net/u/Hyacinth_Dy/p/MyCode/git/blob/master/%E9%9D%A2%E8%AF%95%E9%A2%984-%E9%87%8D%E5%BB%BA%E4%BA%8C%E5%8F%89%E6%A0%91

0 0
原创粉丝点击