#include <iostream>
using namespace std;
#include <stdlib.h>
typedef int Type;
struct BiNode
{
Type data;
BiNode *L,*R;
};
void CreatTree(BiNode *ptr)
{/*?èDòê?è?£?μY1éμ÷ó?
*/
Type data;
cin>>data;
if(!data)
ptr=NULL;
else
{
ptr=new BiNode;
if(!ptr)
exit(0);
(*ptr).data=data;
CreatTree((*ptr).L);
CreatTree((*ptr).R);
}
// return ptr;
}
void PrePrint(BiNode *ptr)
{
if(ptr!=NULL)
{
cout<<ptr->data<<"" "";
PrePrint(ptr->L);
PrePrint(ptr->R);
}
}
int main()
{
BiNode T;
BiNode *Tptr=&T;
CreatTree(Tptr);
// cout<<(*Tptr).data<<endl;
PrePrint(Tptr);
return 0;
}
|
|
| 20分 |
修改如下:
#include <iostream>
using namespace std;
#include <cstdlib>
typedef int Type;
struct BiNode
{
Type data;
BiNode *L, *R;
};
BiNode* CreatTree()
{
Type data;
BiNode *p;
cin >> data;
if (!data)
p = NULL;
else
{
p = new BiNode;
if (!p) exit(0);
p->data = data;
cout << "请输入 " << data << " 节点的左孩子 ";
p->L = CreatTree();
cout << "请输入 " << data << " 节点的右孩子 ";
p->R = CreatTree();
}
return p;
}
void PrePrint(BiNode *ptr)
{
if (ptr != NULL)
{
cout << ptr->data << "" ""; //根
PrePrint(ptr->L); //左
PrePrint(ptr->R); //右
}
}
int main()
{
BiNode *T;
T = CreatTree();
PrePrint(T);
return 0;
}
//1
//请输入 1 节点的左孩子 2
//请输入 2 节点的左孩子 4
//请输入 4 节点的左孩子 0
//请输入 4 节点的右孩子 0
//请输入 2 节点的右孩子 0
//请输入 1 节点的右孩子 3
//请输入 3 节点的左孩子 0
//请输入 3 节点的右孩子 0
//1 2 4 3
|