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

SDUT 216 数据结构实验之二叉树的建立与遍历

2013-06-28 19:59 423 查看
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <iostream>

using namespace std;

struct N
{
char data;
N *l,*r;
};

N *creat()
{
N *p = (N *)malloc(sizeof(N));
p->l = p->r = NULL;
return p;
}

int site = 0;

bool insert(N *root,char *s)
{
if(s[site] == '\0')
return false;

if(s[site] == ',')
{
root = NULL;
site++;
return true;
}
else
{
root->data = s[site++];
root->l = creat();
if(insert(root->l,s))
root->l = NULL;
root->r = creat();
if(insert(root->r,s))
root->r = NULL;
return false;
}
}

void output1(N *root)
{
if(root == NULL)
return ;
output1(root->l);
cout<<root->data;
output1(root->r);
}

void output2(N *root)
{
if(root == NULL)
return ;

if(root->l == NULL && root->r == NULL)
{
cout<<root->data;
return ;
}

output2(root->l);
output2(root->r);
cout<<root->data;
}

int ans;

void depth(N *root,int dep)
{

if(ans < dep)
ans = dep;

if(root == NULL)
return ;
depth(root->l,dep+1);
depth(root->r,dep+1);
}

void leaf(N *root)
{
if(root == NULL)
return ;
if(root->l == NULL && root->r == NULL)
ans++;
leaf(root->l);
leaf(root->r);
}

int main()
{
char s[51];

N *root = creat();

cin>>s;

int i ,l;

site = 0;

insert(root,s);

output1(root);
cout<<endl;
output2(root);
cout<<endl;

ans = 0;

leaf(root);

cout<<ans<<endl;

ans = 0;

depth(root,0);

cout<<ans<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: