二叉树中序和先序,创建二叉树----笔记DevC++
下面展示一些 内联代码片
。
DevC++
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//二叉树的节点
typedef struct TreeNode{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int a):data(a),left(NULL),right(NULL){}
TreeNode():data(0),left(NULL),right(NULL){}
}*BiTree,TreeNode;
BiTree ProAIntCreateTree(int *A,int lowA,int highA,int *B,int lowB,int highB){
BiTree root=(TreeNode*)malloc(sizeof(TreeNode));
root->data=A[lowA];
int i=1;
for(i;B[i]!=root->data;i++);
int llen=i-lowB;
int rlen=highB-i;
if(llen)
root->left=ProAIntCreateTree(A,lowA+1,lowA+llen,B,lowB,lowB+llen-1);//左子树,就都采用以low进行相关操作
else
root->left=NULL;
if(rlen)
root->right=ProAIntCreateTree(A,highA-rlen+1,highA,B,highB-rlen+1,highB);//右子树,就用high相关进行操作
else
root->right=NULL;
return root;
}
void PostOrder(BiTree root){
if(root!=NULL){
PostOrder(root->left);
PostOrder(root->right);
cout<<root->data<<" ";
}
}
int main(){
int n;
cin>>n;
int *A=(int *)malloc(sizeof(int)*(n+1));
int *B=(int *)malloc(sizeof(int)*(n+1));
for(int i=1;i<=n;i++)
cin>>A[i];
for(int i=1;i<=n;i++)
cin>>B[i];
BiTree root=ProAIntCreateTree(A,1,n,B,1,n);
PostOrder(root);
}
//A[1..n],B[1..n]
BiTree create(int *A,int l1,int h1,int *B,int l2,int h2){
BiTree root=(TreeNode*)malloc(sizeof(TreeNode));
root->data=A[l1];
}