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

根据先序序列和中序序列的特点我们可以知道:
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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值