二叉树(2)之二叉树的基本操作(遍历,找节点个数)

二叉树(2)之二叉树的基本操作(遍历,找节点个数)

最难的也就是层次遍历:各种遍历函数其实就是各种递归。叶子节点,深度,总节点,掌握性质都不难‘’

层次遍历

层次遍历,就是从上到下一层一层的遍历 
例如:这里写图片描述


思路:

 

 

这里写图片描述

上代码:层次遍历暂时没用真正的队列不够原理上是一样的。(以后能力提高了在搞)

#include<algorithm> 
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue> 
using namespace std;
typedef struct bitnode//处理前面和这有关后面基本上和这无关 
{
	char  data;//shurudshuju
    struct	bitnode *lchild, *rchild; //houzaohanshu
}bitnode, *bittree;
void create(bittree &t)
{
	char c;
	cin >> c;
	if(c=='#')
		t = NULL ;
	else 
	{
		t=new bitnode;
		t->data = c;	
		create(t->lchild);
		create(t->rchild);
	 } 
}
void xianxu(bittree t)
{
	if(t==NULL)
		return ;
	else
	{
		cout<<t->data;
		xianxu(t->lchild);
		xianxu(t->rchild);
	}
}
void zhongxu(bittree t)
{
	if(t==NULL)
		return  ;
	else
	{
		zhongxu(t->lchild);
		cout<<t->data;
		zhongxu(t->rchild);
	} 
}
void houxu(bittree t)
{
	if(t==NULL)
		return ;
	else 
	{
		houxu(t->lchild);
		houxu(t->rchild);
		cout<<t->data;
	}
}
int deep(bittree t)
{
	int d1=0,d2=0;
	if(t==NULL)
		return 0;
	else 
	{
		d1=deep(t->lchild)+1;
		d2=deep(t->rchild)+1;
	}
	return d1>=d2?d1:d2;
}
//yezhishu
int yezhi(bittree t)
{
	if(t==NULL)
	return 0;
	if(t->lchild==NULL&&t->rchild==NULL)
	return 1;
	else 
	{
		return yezhi(t->lchild) + yezhi(t->rchild);
	}
}
int jiedian(bittree t)
{
	if(t == NULL)
	return 0;
	else
		return jiedian(t->lchild)+jiedian(t->rchild)+1;
}
void cengci(bittree t)
{
	bittree q;
	bittree queue[10];
	int front = 0, rear = 0;
	if(t == NULL)
		return ;
	else 
	{
		rear = (rear+1)%10;
		queue[rear]=t;
		while(front!=rear)
		{
			front=(front+1)%10;
			q=queue[front];
			cout<<q->data;
			if(q->lchild!=NULL)
			{
				rear=(rear+1)%10;
				queue[rear]=q->lchild;
			}
			if(q->rchild!=NULL)
			{
				rear = (rear+1)%10;
				queue[rear]=q->rchild;
			}
		}
	}
} 
int main()
{
	bittree T;
	cout<<"jianshu:"<<endl;
	create(T);
	cout<<endl;
	cout<<"qianxu:"<<endl;
	xianxu(T);
	cout<<endl;
	cout<<"zhongxu"<<endl;
	zhongxu(T);
	cout<<endl;
	cout<<"houxu"<<endl;
	houxu(T);
	cout<<endl;
	cout<<yezhi(T)<<" "<<jiedian(T)<<"  "<<deep(T)<<endl;
	cengci(T);
	return 0;
}
//ABC##DE#G##F###

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/114882.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号