一、前言
前文《直观的打印树结构》已经完成了树结构打印,接下来需要一颗二叉树,那就重建一颗二叉树。
《直观的打印树结构》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