【数据结构】【C++】二叉树的建立和先序遍历----(1)
今晚搞清楚了二叉树的建立和先序遍历,不过现在已经是0:32了,该睡觉了,贴上代码,明天补充细节,加油,晚安!
==============分割线=====================
#include<iostream>
#include <malloc.h>
#include<stdio.h>
using namespace std;
struct node
{
int data;
struct node* left;
struct node* right;
};
void visit(node* BT);
node* creat();
node* creat(node* &T);
void preOrder(node*T);
int main()
{
node* BT;
BT=creat();
preOrder(BT);
return 0;
}
void visit(node* BT)
{
cout<<BT->data<<' ';
//cout<<"hi"<<endl;
}
node* creat()
{
node* T;
int num;
scanf("%d",&num);
if(num=='0')
T=NULL;
else
{
T = (node*)malloc(sizeof(node));
T->data = num;
//cout<<num;
T->left = creat();
T->right = creat();
}
return T;
}
void preOrder(node*T)
{
if(T==NULL)
return;
else
{
visit(T);
preOrder(T->left);
preOrder(T->right);
}
}