您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树二:遍历二叉树

2016-08-08 11:34 162 查看
题目链接

#include<stdio.h>
#include<cstring>
#include<string>
#include<iostream>
#include<algorithm>

using namespace std;

string a;
int l1;

typedef struct node
{
char data;
struct node *lchild,*rchild;
}Tree;

struct node *creat()///先序建立二叉树
{
Tree *root;
char c;
c=a[l1++];
if(c==',')
return NULL;
else
{
root=new Tree;
root->data=c;
root->lchild=creat();
root->rchild=creat();

}
return root;
}

void intree(Tree *root)
{
if(root!=NULL)
{
intree(root->lchild);
cout<<root->data;
intree(root->rchild);
}
}

void lastree(Tree *root)
{
if(root!=NULL)
{
lastree(root->lchild);
lastree(root->rchild);
cout<<root->data;
}
}

int leave(struct node *root)///统计叶子数
{
if(root==NULL)
return 0;
if(root->lchild==NULL&&root->rchild==NULL)
return 1;
else
return leave(root->lchild)+leave(root->rchild);
}

int main()
{
Tree *root;
while(cin>>a)
{
l1=0;
root=new Tree;
root=creat();
intree(root);
cout<<endl;
lastree(root);
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: