当前位置:网站首页>Establish binary tree + C language code from preorder and middle order
Establish binary tree + C language code from preorder and middle order
2022-07-28 15:12:00 【Demon YoY】
summary
describe :
Given a preorder ( In the following order ) And middle order to build a binary tree , For example, the sequence of precedence :ABDCEF, Subsequent sequence :BDAECF
Build a binary tree
recursive
The first node of the preorder traversal is the root node . In the sequence traversed by middle order , On the left side of this node is the left subtree , On the right side of this node is the right subtree .
If the left subtree is not empty , Then the second node of the preorder traversal is the root node of the left subtree , Otherwise, it is the root node of the right subtree . Repeat the above steps for the left and right subtrees , Can uniquely determine a binary tree .
( The latter sequence should be from the back to the front )
Code
#include <stdio.h>
struct TNode{
char data;
struct TNode* left;
struct TNode* right;
};
TNode* piTree(char *pa, char *ia, int p1, int p2, int i1, int i2)
{
int ia_mid;
TNode *T;
T=new TNode;
T->data=pa[p1];
T->left=T->right=NULL;
if(p1>p2 || i1>i2)
return NULL;
for(ia_mid=0;;ia_mid++){
if(pa[p1]==ia[ia_mid])
break;
}// Find the root node in the middle order sequence
T->left = piTree(pa,ia,p1+1,p1+(ia_mid-i1),i1,ia_mid-1);
T->right = piTree(pa,ia,p1+(ia_mid-i1)+1,p2,ia_mid+1,i2);
return T;
}
void PostTravel(TNode* T)
{
// Post sequence printing
if(T==NULL) return;
if(T->left) PostTravel(T->left);
if(T->right) PostTravel(T->right);
printf("%c", T->data);
}
int main()
{
char pre[100], in[100];
int n; // Used to save the sequence length
TNode *T; // Used to save the root of binary tree
printf(" Input sequence :\n");
scanf("%s", pre);
printf(" Input medium sequence :\n");
scanf("%s", in);
n=0;
while(pre[n]) n++; // Calculate the length of the sequence
T= piTree(pre, in, 0, n-1, 0, n-1);
printf(" Subsequent sequence :\n");
PostTravel(T); // Print sequence
return 0;
}
Examples of run results :
边栏推荐
猜你喜欢
随机推荐
Use of beefs
Deploy flask on Alibaba cloud server
知识产权相关的风险评估要怎么做
URP下使用GL进行绘制方法
Establishment and traversal of binary tree (implemented in C language)
List of security technologies to be considered in cloud computing
即刻体验 | 借助 CTS-D 进一步提升应用设备兼容性
Instant experience | further improve application device compatibility with cts-d
安装mosek,license安装位置查找
@DS('slave') 多数据源兼容事务问题解决方案
9、 C array explanation
4518. 最低票价
7、 Detailed explanation of C language function definition
QT qlineedit, qtextedit, qplaintextedit differences
Chapter I Introduction
Privacy computing summary
Chapter 3 stack, queue and array
PHP magic method
Matlab load usage
15、 Launch file label of ROS (I)









