二叉树的生成和递归遍历

1.遍历时要注意判断递归结束的条件if(T)

2.临时节点变量创建是否成功判断

#include <iostream>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

typedef struct btnode{
char data;
struct btnode *lchild;
struct btnode *rchild;
}btnode;

void addbitree(btnode *T , btnode *p);
void preorder(btnode *T);
void inorder(btnode *T);
void postorder(btnode *T);

int main(){
btnode *root,*p;
cout << "please input data(use space reprent the end)" <<endl;
char ch;
cin >> ch;
root = NULL;
while(ch != ' ')
{
// cout << ch <<endl;
if(p = (btnode *)malloc(sizeof(btnode))){  //2.临时节点变量创建是否成功判断
p->data = ch;
p->lchild = NULL;
p->rchild = NULL;
}
else{
cout << "error" <<endl;
exit(0);
}
if(root == NULL){
root = p;
}
else{
addbitree(root , p);
}
ch = getchar();//cin不能识别空格,tab或者enter
}
cout << "preorder " <<endl;
preorder(root);

cout << "ineorder " <<endl;
inorder(root);

cout << "posteorder " <<endl;
postorder(root);

return 0;
}

void addbitree(btnode *T, btnode *p){
if(((p->data) <= (T->data))&&(T->lchild)==NULL ){
T->lchild = p;
}
else if((p->data <=(T->data))&&(T->lchild)!=NULL){
addbitree(T->lchild,p);
}
else if((T->rchild)==NULL){
T->rchild = p;
}
else
addbitree(T->rchild,p);
cout << p->data <<endl;
}


void preorder(btnode *T){
if(T){  //遍历时要注意判断递归结束的条件if(T)
cout << T->data <<" ";
preorder(T->lchild);
preorder(T->rchild);
}
}
void inorder(btnode *T){
if(T){
inorder(T->lchild);
cout << T->data <<" ";
inorder(T->rchild);
}
}


void postorder(btnode *T){
if(T){
postorder(T->lchild);
postorder(T->rchild);
cout << T->data <<" ";
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值