//基于递归的二叉树遍历
#include<stdio.h>
#include<stdlib.h>
struct TreeNode{
int val;
TreeNode *left,*right;
};
TreeNode *insertTree(TreeNode *root,int val){
TreeNode *newNode;
if(root==NULL){
newNode=new TreeNode;
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
if(val<=root->val)
root->left=insertTree(root->left,val);
else
root->right=insertTree(root->right,val);
return root;
}
void delTree(TreeNode *root){
if(root->left!=NULL)
delTree(root->left);
if(root->right!=NULL)
delTree(root->right);
delete root;
}
void LFRTraverse(TreeNode *root){
if(root->left!=NULL)
LFRTraverse(root->left);
printf("%d-",root->val);
if(root->right!=NULL)
LFRTraverse(root->right);
}
void FLRTraverse(TreeNode *root){
printf("%d-",root->val);
if(root->left!=NULL)
FLRTraverse(root->left);
if(root->right!=NULL)
FLRTraverse(root->right);
}
int main()
{
FILE *fin;
TreeNode *root;
int val;
char inFile[30];
printf("input the data file's name:\n");
scanf("%s",inFile);
fin=fopen(inFile,"r");
root=NULL;
while(fscanf(fin,"%d",&val)!=EOF)
root=insertTree(root,val);
fclose(fin);
printf("traversing left sub-tree firstly,then root,and right sub-tree lastly:\n");
LFRTraverse(root);
printf("\n");
printf("traversing root firstly,then left sub-tree,and right sub-tree lastly:\n");
FLRTraverse(root);
printf("\n");
delTree(root);
return 0;
}
基于递归的二叉树遍历
最新推荐文章于 2020-03-17 23:42:37 发布