已知二叉树前序和中序建立二叉树,要求C++实现
时间: 2024-02-04 16:50:49 浏览: 82
#include<stdio.h>
#include<stdlib.h>
typedef struct treenode{
char data;
struct treenode* left;
struct treenode* right;
}TreeNode;
TreeNode* buildTree(char* preOrder, char* inOrder, int length){
if(preOrder==NULL||inOrder==NULL||length<=0){
return NULL;
}
TreeNode* root=(TreeNode*)malloc(sizeof(TreeNode));
root->data=*preOrder;
root->left=NULL;
root->right=NULL;
int rootIndex=-1;
for(int i=0;i<length;i++){
if(inOrder[i]==*preOrder){
rootIndex=i;
break;
}
}
if(rootIndex==-1){
printf("Invalid Input!\n");
return NULL;
}
root->left=buildTree(preOrder+1,inOrder,rootIndex);
root->right=buildTree(preOrder+rootIndex+1,inOrder+rootIndex+1,length-rootIndex-1);
return root;
}
void preOrderTraverse(TreeNode* root){
if(root==NULL){
return;
}
printf("%c ",root->data);
preOrderTraverse(root->left);
preOrderTraverse(root->right);
}
void inOrderTraverse(TreeNode* root){
if(root==NULL){
return;
}
inOrderTraverse(root->left);
printf("%c ",root->data);
inOrderTraverse(root->right);
}
int main(){
char preOrder[]={'A','B','D','E','C','F','G'};
char inOrder[]={'D','B','E','A','F','C','G'};
TreeNode* root=buildTree(preOrder,inOrder,7);
printf("PreOrder Traverse: ");
preOrderTraverse(root);
printf("\nInOrder Traverse: ");
inOrderTraverse(root);
return 0;
}
阅读全文