#include<iostream>
#include <string>
using namespace std;
//结构体
typedef struct node
{
char data;
struct node *lchild,*rchild;
}binary_tree,*tree;
//构造一棵树,以字符0作为空
void creat_tree(tree &t)
{
char ch;
cin>>ch;
if(ch == '0')
{
t=NULL;
}
else
{
t = new binary_tree;
if(!t) exit(0); //如果没成功申请空间 则退出
t->data=ch;
creat_tree(t->lchild);
creat_tree(t->rchild);
}
}
//打印路径
bool printPath(tree &t, char data)
{
if (t == NULL)
return false;
if (t->data == data || printPath(t->lchild,data) || printPath(t->rchild,data))
{
cout<<t->data; //路径上的结点标识打印出来
return true;
}
return false;
}
//输出路径长度
void printLeavesDepth(tree &t, size_t depth = 0)
{
if (t == NULL) return;
if (t->lchild == NULL && t->rchild == NULL)
{
cout<<t->data<<": "<<depth<<endl;
}
else
{
printLeavesDepth(t->lchild, depth+1);
printLeavesDepth(t->rchild, depth+1);
}
}
//输出叶子结点值
void DispLeaf(tree &t)
{
if(t)
{
if(t->lchild==NULL&&t->rchild==NULL)
{
cout<<t->data<<" ";
}
DispLeaf(t->lchild);
DispLeaf(t->rchild);
}
}
int main()
{
tree t;
cout<<"请输入二叉树节点:(例如输入:ab00c00)";
creat_tree(t);
cout<<"输出叶子结点"<<endl;
DispLeaf(t);
cout<<endl;
cout<<"各个叶子结点到根结点的路径长度"<<endl;
printLeavesDepth(t,0);
system("pause");
return 0;
}
版权声明:本文为u012967763原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。