根据前序中序序列构建二叉树

2024-06-22 22:48

本文主要是介绍根据前序中序序列构建二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  

  

  问题描述:

    输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

  思路:

  在二叉树的前序遍历序列中,第一个数字总是树的根结点的值。但在中序遍历序列中,根结点的值在序列的中间,左子树的结点的值位于根结点的值的左边,而右子树的结点的值位于根结点的值的右边。因此我们需要扫描中序遍历序列,才能找到根结点的值。

  如下图所示,前序遍历序列的第一个数字1就是根结点的值。扫描中序遍历序列,就能确定根结点的值的位置。根据中序遍历特点,在根结点的值1前面的3个数字都是左子树结点的值,位于1后面的数字都是右子树结点的值。

 

 

  

  同样,在前序遍历的序列中,根结点后面的3个数字就是3个左子树结点的值,再后面的所有数字都是右子树结点的值。这样我们就在前序遍历和中序遍历两个序列中,分别找到了左右子树对应的子序列。

  既然我们已经分别找到了左、右子树的前序遍历序列和中序遍历序列,我们可以用同样的方法分别去构建左右子树。也就是说,接下来的事情可以用递归的方法去完成。
  完整的代码示例如下,方式一使用数组存储前序遍历序列和中序遍历序列;方式二使用容器存储。

/*
题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
*//*
思路:
先序遍历的第一个元素为根节点,在中序遍历中找到这个根节点,从而可以将中序遍历分为左右两个部分,
左边部分为左子树的中序遍历,右边部分为右子树的中序遍历,进而也可以将先序遍历除第一个元素以外的剩余部分分为两个部分,
第一个部分为左子树的先序遍历,第二个部分为右子树的先序遍历。
由上述分析结果,可以递归调用构建函数,根据左子树、右子树的先序、中序遍历重建左、右子树。
*/
/*
Time:2016年9月9日11:57:07
Author:CodingMengmeng
*//*
方式一:数组+递归
*/
#include <iostream>
using namespace std;//树结点结构体
struct BinaryTreeNode
{int                    m_nValue;BinaryTreeNode*        m_pLeft;BinaryTreeNode*        m_pRight;};//打印树结点
void PrintTreeNode(BinaryTreeNode *pNode)
{if (pNode != NULL){printf("value of this node is : %d\n", pNode->m_nValue);if (pNode->m_pLeft != NULL)printf("value of its left child is: %d.\n", pNode->m_pLeft->m_nValue);elseprintf("left child is null.\n");if (pNode->m_pRight != NULL)printf("value of its right childe is : %d.\n", pNode->m_pRight->m_nValue);elseprintf("right child is null.\n");}else{printf("this node is null.\n");}printf("\n");
}
void PrintTree(BinaryTreeNode *pRoot)
{PrintTreeNode(pRoot);//   if (pRoot != NULL){if (pRoot->m_pLeft != NULL)PrintTree(pRoot->m_pLeft);if (pRoot->m_pRight != NULL)PrintTree(pRoot->m_pRight);}
}/*
preorder 前序遍历
inorder 中序遍历*/BinaryTreeNode* ConstructCore(int* startPreorder, int* endPreorder, int* startInorder, int* endInorder);
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);}// startPreorder 前序遍历的第一个节点  
// endPreorder   前序遍历的最后后一个节点  
// startInorder  中序遍历的第一个节点  
// startInorder  中序遍历的最后一个节点  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 = root->m_pRight = NULL;// 只有一个结点if (startPreorder == endPreorder){if (startInorder == endInorder && *startPreorder == *startInorder)return root;elsethrow std::exception("Invalid input.");}//有多个结点// 在中序遍历中找到根结点的值  int *rootInorder = startInorder;while (rootInorder <= endInorder && *rootInorder != rootValue)++rootInorder;if (rootInorder == endInorder && *rootInorder != rootValue)throw std::exception("Invalid input");//  int leftLength = rootInorder - startInorder;    //中序序列的左子树序列长度int *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;
}// 测试代码  
void Test(char *testName, int *preorder, int *inorder, int length)
{if (testName != NULL)printf("%s Begins:\n", testName);printf("The preorder sequence is: ");for (int i = 0; i < length; ++i)printf("%d ", preorder[i]);printf("\n");printf("The inorder sequence is:");for (int i = 0; i < length; ++i)printf("%d ", inorder[i]);printf("\n");try{BinaryTreeNode *root = Construct(preorder, inorder, length);PrintTree(root);}catch (std::exception &expection){printf("Invalid Input.\n");}
}// 普通二叉树  
//              1  
//           /     \  
//          2       3    
//         /       / \  
//        4       5   6  
//         \         /  
//          7       8  
void Test1()
{const int length = 8;int preorder[length] = { 1, 2, 4, 7, 3, 5, 6, 8 };int inorder[length] = { 4, 7, 2, 1, 5, 3, 8, 6 };Test("Test1", preorder, inorder, length);
}int main()
{Test1();  system("pause");return 0;
}/*
输出结果:
----------------------------------------------------------------
Test1 Begins:
The preorder sequence is: 1 2 4 7 3 5 6 8
The inorder sequence is:4 7 2 1 5 3 8 6
value of this node is : 1
value of its left child is: 2.
value of its right childe is : 3.value of this node is : 2
value of its left child is: 4.
right child is null.value of this node is : 4
left child is null.
value of its right childe is : 7.value of this node is : 7
left child is null.
right child is null.value of this node is : 3
value of its left child is: 5.
value of its right childe is : 6.value of this node is : 5
left child is null.
right child is null.value of this node is : 6
value of its left child is: 8.
right child is null.value of this node is : 8
left child is null.
right child is null.请按任意键继续. . .
----------------------------------------------------------------*//*
方式二:容器+递归
*/#include <iostream>
#include <vector>
using namespace std;// Definition for binary tree
struct TreeNode {int val;TreeNode *left;TreeNode *right;TreeNode(int x) : val(x), left(NULL), right(NULL) {}};/* 先序遍历第一个位置肯定是根节点node,中序遍历的根节点位置在中间p,在p左边的肯定是node的左子树的中序数组,p右边的肯定是node的右子树的中序数组另一方面,先序遍历的第二个位置到p,也是node左子树的先序子数组,剩下p右边的就是node的右子树的先序子数组把四个数组找出来,分左右递归调用即可*/class Solution {public:struct TreeNode* reConstructBinaryTree(vector<int> pre, vector<int> in) {int in_size = in.size();//获得序列的长度if (in_size == 0)return NULL;//分别存储先序序列的左子树,先序序列的右子树,中序序列的左子树,中序序列的右子树vector<int> pre_left, pre_right, in_left, in_right;int val = pre[0];//先序遍历第一个位置肯定是根节点node,取其值//新建一个树结点,并传入结点值TreeNode* node = new TreeNode(val);//root node is the first element in pre//p用于存储中序序列中根结点的位置int p = 0;for (p; p < in_size; ++p){if (in[p] == val) //Find the root position in in break;        //找到即跳出for循环}for (int i = 0; i < in_size; ++i){if (i < p){//建立中序序列的左子树和前序序列的左子树in_left.push_back(in[i]);//Construct the left pre and in pre_left.push_back(pre[i + 1]);//前序第一个为根节点,+1从下一个开始记录}else if (i > p){//建立中序序列的右子树和前序序列的左子树in_right.push_back(in[i]);//Construct the right pre and in pre_right.push_back(pre[i]);}}//取出前序和中序遍历根节点左边和右边的子树//递归,再对其进行上述所有步骤,即再区分子树的左、右子子数,直到叶节点node->left = reConstructBinaryTree(pre_left, in_left);node->right = reConstructBinaryTree(pre_right, in_right);return node;}};
    #include <stdlib.h> #include <stdio.h> typedef struct TNode { int value; TNode* lchild; TNode* rchild; }TNode,*BTree;  //根据先序遍历、中序遍历构建二叉树 BTree rebuild(int preOrder[],int startPre,int endPre,int inOrder[],int startIn,int endIn) { //先序遍历和中序遍历长度应相等 if (endPre - startPre != endIn - startIn) return NULL; //起始位置不应大于末尾位置 if (startPre > endPre) return NULL; //先序遍历的第一个元素为根节点 BTree tree = (BTree)malloc(sizeof(TNode)); tree->value = preOrder[startPre]; tree->lchild = NULL; tree->rchild = NULL; //先序遍历和中序遍历只有一个元素时,返回该节点 if (startPre == endPre) return tree; //在中序遍历中找到根节点 int index,length; for (index=startIn;index<=endIn;index++) { if (inOrder[index] == preOrder[startPre]) break; } //若未找到,返回空 if (index > endIn) return NULL; //有左子树,递归调用构建左子树 if (index > startIn)  { length = index-startIn; tree->lchild = rebuild(preOrder,startPre+1,startPre+1+length-1,inOrder,startIn,startIn+length-1); } //有右子树,递归调用构建右子树 if (index < endIn)  { length = endIn - index; tree->rchild = rebuild(preOrder,endPre-length+1,endPre,inOrder,endIn-length+1,endIn); } return tree; } //后序遍历二叉树 void postTraverse(BTree tree) { if (tree->lchild != NULL) postTraverse(tree->lchild); if (tree->rchild != NULL) postTraverse(tree->rchild); printf("%d ",tree->value); } int main() { int preOrder[] = {1,2,4,5,3,6}; int inOrder[] = {4,2,5,1,6,3}; BTree tree = rebuild(preOrder,0,5,inOrder,0,5); postTraverse(tree); printf("\n"); return 0; } 



这篇关于根据前序中序序列构建二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1085629

相关文章

Three.js构建一个 3D 商品展示空间完整实战项目

《Three.js构建一个3D商品展示空间完整实战项目》Three.js是一个强大的JavaScript库,专用于在Web浏览器中创建3D图形,:本文主要介绍Three.js构建一个3D商品展... 目录引言项目核心技术1. 项目架构与资源组织2. 多模型切换、交互热点绑定3. 移动端适配与帧率优化4. 可

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

Python利用PySpark和Kafka实现流处理引擎构建指南

《Python利用PySpark和Kafka实现流处理引擎构建指南》本文将深入解剖基于Python的实时处理黄金组合:Kafka(分布式消息队列)与PySpark(分布式计算引擎)的化学反应,并构建一... 目录引言:数据洪流时代的生存法则第一章 Kafka:数据世界的中央神经系统消息引擎核心设计哲学高吞吐

Springboot项目构建时各种依赖详细介绍与依赖关系说明详解

《Springboot项目构建时各种依赖详细介绍与依赖关系说明详解》SpringBoot通过spring-boot-dependencies统一依赖版本管理,spring-boot-starter-w... 目录一、spring-boot-dependencies1.简介2. 内容概览3.核心内容结构4.

Go语言使用net/http构建一个RESTful API的示例代码

《Go语言使用net/http构建一个RESTfulAPI的示例代码》Go的标准库net/http提供了构建Web服务所需的强大功能,虽然众多第三方框架(如Gin、Echo)已经封装了很多功能,但... 目录引言一、什么是 RESTful API?二、实战目标:用户信息管理 API三、代码实现1. 用户数据

Linux中的自定义协议+序列反序列化用法

《Linux中的自定义协议+序列反序列化用法》文章探讨网络程序在应用层的实现,涉及TCP协议的数据传输机制、结构化数据的序列化与反序列化方法,以及通过JSON和自定义协议构建网络计算器的思路,强调分层... 目录一,再次理解协议二,序列化和反序列化三,实现网络计算器3.1 日志文件3.2Socket.hpp

使用Python构建智能BAT文件生成器的完美解决方案

《使用Python构建智能BAT文件生成器的完美解决方案》这篇文章主要为大家详细介绍了如何使用wxPython构建一个智能的BAT文件生成器,它不仅能够为Python脚本生成启动脚本,还提供了完整的文... 目录引言运行效果图项目背景与需求分析核心需求技术选型核心功能实现1. 数据库设计2. 界面布局设计3

深入浅出SpringBoot WebSocket构建实时应用全面指南

《深入浅出SpringBootWebSocket构建实时应用全面指南》WebSocket是一种在单个TCP连接上进行全双工通信的协议,这篇文章主要为大家详细介绍了SpringBoot如何集成WebS... 目录前言为什么需要 WebSocketWebSocket 是什么Spring Boot 如何简化 We

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核