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

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

相关文章

Spring Cloud:构建分布式系统的利器

引言 在当今的云计算和微服务架构时代,构建高效、可靠的分布式系统成为软件开发的重要任务。Spring Cloud 提供了一套完整的解决方案,帮助开发者快速构建分布式系统中的一些常见模式(例如配置管理、服务发现、断路器等)。本文将探讨 Spring Cloud 的定义、核心组件、应用场景以及未来的发展趋势。 什么是 Spring Cloud Spring Cloud 是一个基于 Spring

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测

时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测 目录 时序预测 | MATLAB实现LSTM时间序列未来多步预测-递归预测基本介绍程序设计参考资料 基本介绍 MATLAB实现LSTM时间序列未来多步预测-递归预测。LSTM是一种含有LSTM区块(blocks)或其他的一种类神经网络,文献或其他资料中LSTM区块可能被描述成智能网络单元,因为

Python应用开发——30天学习Streamlit Python包进行APP的构建(9)

st.area_chart 显示区域图。 这是围绕 st.altair_chart 的语法糖。主要区别在于该命令使用数据自身的列和指数来计算图表的 Altair 规格。因此,在许多 "只需绘制此图 "的情况下,该命令更易于使用,但可定制性较差。 如果 st.area_chart 无法正确猜测数据规格,请尝试使用 st.altair_chart 指定所需的图表。 Function signa

剑指offer(C++)--平衡二叉树

题目 输入一棵二叉树,判断该二叉树是否是平衡二叉树。 class Solution {public:bool IsBalanced_Solution(TreeNode* pRoot) {if(pRoot==NULL)return true;int left_depth = getdepth(pRoot->left);int right_depth = getdepth(pRoot->rig

二叉树三种遍历方式及其实现

一、基本概念 每个结点最多有两棵子树,左子树和右子树,次序不可以颠倒。 性质: 1、非空二叉树的第n层上至多有2^(n-1)个元素。 2、深度为h的二叉树至多有2^h-1个结点。 3、对任何一棵二叉树T,如果其终端结点数(即叶子结点数)为n0,度为2的结点数为n2,则n0 = n2 + 1。 满二叉树:所有终端都在同一层次,且非终端结点的度数为2。 在满二叉树中若其深度为h,则其所包含

LeetCode 算法:二叉树的中序遍历 c++

原题链接🔗:二叉树的中序遍历 难度:简单⭐️ 题目 给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。 示例 1: 输入:root = [1,null,2,3] 输出:[1,3,2] 示例 2: 输入:root = [] 输出:[] 示例 3: 输入:root = [1] 输出:[1] 提示: 树中节点数目在范围 [0, 100] 内 -100 <= Node.

基于Spring Boot构建淘客返利平台

基于Spring Boot构建淘客返利平台 大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将讨论如何基于Spring Boot构建一个淘客返利平台。 淘客返利平台通过整合各种电商平台的商品信息,提供给用户查询和返利功能,从而实现流量变现。以下是实现一个简单的淘客返利平台的步骤。 1. 项目初始化 首先,使用Spri

代码随想录——摆动序列(Leetcode376)

题目链接 贪心 class Solution {public int wiggleMaxLength(int[] nums) {if(nums.length <= 1){return nums.length;}// 当前一对差值int cur = 0;// 前一对差值int pre = 0;// 峰值个数int res = 1;for(int i = 0; i < nums.length -

C++ 重建二叉树(递归方法)

/*** struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* };*/#include <vector>class Solution {public:/*** 代码

想让Python序列切片更高效?这些技巧你不可不知!

目录 1、自定义类实现切片 🍏 1.1 实现__getitem__方法 1.2 支持正负索引与步长 2、利用 collections.abc 模块 🧠 2.1 继承MutableSequence类 2.2 重写关键方法 3、使用标准库itertools.slice 🍲 3.1 itertools工具介绍 3.2 slice函数应用实例 4、通过生成器实现动态切片 🌀