您的位置:首页 > 理论基础 > 数据结构算法

二叉树重建及遍历

2015-09-17 03:06 507 查看
        树是一种在实际编程中经常遇到的数据结构。它的逻辑很简单:除了根结点之外每个结点只有一个父结点,根节点没有父结点;除了叶结点之外所有结点都有一个或多个子结点,叶结点没有子结点。

        二叉树的遍历方式:

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

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

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

题目:输入某二叉树的前序遍历和中序遍历的结果,重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

// 重建二叉树.cpp : 定义控制台应用程序的入口点。
//输入某二叉树的前序遍历和中序遍历的结果,重建出该二叉树,
//假设输入的前序遍历和中序遍历的结果中不含重复的数字

#include "stdafx.h"
#include<iostream>
using namespace std;

typedef int ElemType;

struct BinaryTreeNode
{
ElemType m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};

BinaryTreeNode* ConstructCore(int* startpreorder, int* endpreorder, int* startinorder, int* endinorder)
{
int rootValue = startpreorder[0];
BinaryTreeNode* root = new BinaryTreeNode();
root->m_nValue = rootValue;
root->m_pLeft = NULL;
root->m_pRight = NULL;

if (startpreorder == endpreorder)
{
if (startinorder == endinorder && *startpreorder == *startinorder)
{
return root;
}
else
{
throw exception("Invalid input.");
}
}
int* rooInorder = startinorder;
while (rooInorder <= endinorder&&*rooInorder != rootValue)
{
++rooInorder;
}
if (rooInorder == endinorder && *rooInorder != rootValue)
{
throw exception("Invalid input.");
}
int leftLength = rooInorder - startinorder;
int* leftPreorderEnd = startpreorder + leftLength;
if (leftLength > 0)
{
//构建左子树
root->m_pLeft = ConstructCore(startpreorder + 1, leftPreorderEnd, startinorder, rooInorder - 1);
}
if (leftLength < endpreorder - startpreorder)
{
//构建右子树
root->m_pRight = ConstructCore(leftPreorderEnd + 1, endpreorder, rooInorder + 1, endinorder);
}
return root;
}

BinaryTreeNode* Construct(int* preorder, int* inorder, int length)
{
if (preorder == NULL || inorder == NULL || length <= 0)
{
return NULL;
}
return ConstructCore(preorder, preorder + length - 1, inorder, inorder + length - 1);
}

//前序遍历
void PreTraverseBinaryTree(BinaryTreeNode* root)
{
if (root == NULL)
return;

cout << root->m_nValue << "\t";

PreTraverseBinaryTree(root->m_pLeft);
PreTraverseBinaryTree(root->m_pRight);
}
//中序遍历
void InTraverseBinaryTree(BinaryTreeNode* root)
{
if (root == NULL)
{
return;
}
InTraverseBinaryTree(root->m_pLeft);
cout << root->m_nValue << "\t";
InTraverseBinaryTree(root->m_pRight);
}
int _tmain(int argc, _TCHAR* argv[])
{
int PreOrder[8] = { 1, 2, 4, 7, 3, 5, 6, 8 };
int InOrder[8] = { 4, 7, 2, 1, 5, 3, 8, 6 };
BinaryTreeNode* Root;
Root = Construct(PreOrder, InOrder, 8);
PreTraverseBinaryTree(Root);
cout << endl;
InTraverseBinaryTree(Root);
cout << endl;
return 0;
}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息