数据结构与算法之二叉树遍历


1.创建二叉树节点建立顺序:首先添加根节点,然后添加左孩子,再添加左孩子的左孩子(递归原因导致以左或右为先,该案例先添加左孩子),以此类推,当不再添加左孩子时,然后添加右孩子.当右孩子不添加时,然后函数回调到父节点是否添加右孩子,以此类推,建立二叉树。

#include<iostream>
#include<string>
using namespace std;

struct Node{
  int value;
  Node *leftchild;
  Node *rightchild;
};

Node *create(){
   Node *node;
   int data;
  
   cin>>data;
   if(data==0){
	   return NULL;
   }

   node=new Node;
   node->value=data;
   cout<<"输入"<<node->value<<"左孩子";
   node->leftchild=create();
   cout<<"输入"<<node->value<<"右孩子";
   node->rightchild=create();
   return node;
}

//前序遍历
void preshow(Node *n){
	if(!n)
		return ;
	cout<<n->value<<endl;
	preshow(n->leftchild);
	preshow(n->rightchild);
}

//中续遍历
void inshow(Node *n){
if(!n)
	return;
inshow(n->leftchild);
cout<<n->value;
inshow(n->rightchild);

}
//后序遍历
void lashow(Node *n){

lashow(n->leftchild);
lashow(n->rightchild);
cout<<n->value;
}

int main(){
	Node *t=NULL;
	 cout<<"输入根节点 以数字0结束 "<<endl;
	t=create();
	cout<<"前序遍历"<<endl;
	preshow(t);
	cout<<"中序遍历"<<endl;
	inshow(t);
	cout<<"后序遍历"<<endl;
	lashow(t);
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值