重建二叉树

一、前言

前文《直观的打印树结构》已经完成了树结构打印,接下来需要一颗二叉树,那就重建一颗二叉树。

《直观的打印树结构》https://blog.csdn.net/nie2314550441/article/details/106066834

 

二、题目

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。不含相同的节点值。

 

三、知识点回顾

先回顾一下树的几种遍历方式:

  • 前序遍历:先访问根结点,再访问左子结点,最后访问右子结点。
  • 中序遍历:先访问左子结点,再访问根结点,最后访问右子结点。
  • 后序遍历:先访问左子结点,再访问右子结点,最后访问根结点。

 

四、思路

前序遍历,第一个值为当前根节点,对应找到它在中序遍历中的位置,其左边为树左节点集合,右边为树右节点集合。这样就将树一份为二,以此类推,递归实现即可。

 

五、编码实现

// Common.h
#pragma once

template<class T>
struct BinaryTreeNode
{
    T m_nValue;
    BinaryTreeNode* m_pLeft;
    BinaryTreeNode* m_pRight;
};
// ConstructTree.h
#pragma once
#include <exception>
#include "Common.h"

template<class T>
BinaryTreeNode<T>* ConstructCore(T* startPreorder, T* endPreorder, T* startInorder, T* endInorder);

template<class T>
BinaryTreeNode<T>* Construct(T* preorder, T* inorder, int length)
{
    if (preorder == nullptr || inorder == nullptr || length <= 0)
        return nullptr;

    return ConstructCore(preorder, preorder + length - 1,
        inorder, inorder + length - 1);
}

template<class T>
BinaryTreeNode<T>* ConstructCore
(
    T* startPreorder, T* endPreorder,
    T* startInorder, T* endInorder
)
{
    // 前序遍历序列的第一个数字是根结点的值
    T rootValue = startPreorder[0];
    BinaryTreeNode<T>* root = new BinaryTreeNode<T>();
    root->m_nValue = rootValue;
    root->m_pLeft = root->m_pRight = nullptr;

    if (startPreorder == endPreorder)
    {
        if (startInorder == endInorder && *startPreorder == *startInorder)
            return root;
        else
            throw std::exception("Invalid input.");
    }

    // 在中序遍历中找到根结点的值
    T* rootInorder = startInorder;
    while (rootInorder <= endInorder && *rootInorder != rootValue)
        ++rootInorder;

    if (rootInorder == endInorder && *rootInorder != rootValue)
        throw std::exception("Invalid input.");

    T leftLength = rootInorder - startInorder;
    T* leftPreorderEnd = startPreorder + leftLength;
    if (leftLength > 0)
    {
        // 构建左子树
        root->m_pLeft = ConstructCore(startPreorder + 1, leftPreorderEnd,
            startInorder, rootInorder - 1);
    }
    if (leftLength < endPreorder - startPreorder)
    {
        // 构建右子树
        root->m_pRight = ConstructCore(leftPreorderEnd + 1, endPreorder,
            rootInorder + 1, endInorder);
    }

    return root;
}

六、后续

树重建完成了,从上往下遍历,刚好可以满足上一篇文章中树结构打印,现在缺从上往下打印二叉树。见下一片文章。

从上往下打印二叉树 https://blog.csdn.net/nie2314550441/article/details/106088697

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值