前序遍历和中序遍历重建二叉树

来源:互联网 发布:数控编程专业介绍 编辑:程序博客网 时间:2024/05/16 10:39

根据先序序列和中序序列的特点我们可以知道:
1、先序的第一个节点是根节点
2、在中序序列中,根结点前边的结点都是左子树中的,根结点右边的结点都是右子树中的
3、通过左右子树的中序序列带入前序序列可以求出左右子树的前序序列
4、左右子树的前序序列第一个元素分别是根节点的左右孩子
5、可以递归上述步骤来重建二叉树
具体代码实现:

//前序+中序重建二叉树BinaryTreeNode<T>* _ReBuildTree(int *start_pre, int *end_pre, int *start_in, int *end_in){    int root_val = start_pre[0];//前序遍历第一个结点即为根节点    BinaryTreeNode<T>* pRoot = new BinaryTreeNode<T>(root_val);    pRoot->_pLeftChild = pRoot->_pRightChild = NULL;    if (start_pre == end_pre)    {        if (start_in == end_in && *start_pre == *start_in)            return pRoot;        else            cout << "invalid input" << endl;    }    //在中序序列中找到根节点,根节点左侧为左子树,右侧为右子树    int *root = start_in;    while (root <= end_in && *root != root_val)//中序序列中找根节点        root++;    int leftlen = root - start_in;//左子树的size    int *left_end = start_pre + leftlen;//在前序序列中划分左子树    if (leftlen > 0)//构建左子树    {        pRoot->_pLeftChild = _ReBuildTree(start_pre+1, left_end, start_in, root-1);    }    if (leftlen < end_pre - start_pre)//构建右子树    {        pRoot->_pRightChild = _ReBuildTree(left_end+1, end_pre, root + 1, end_in);    }    return pRoot;}
阅读全文
0 0
原创粉丝点击