数据结构|二叉树的算法C++

一、树的一些术语、操作

1、根节点,叶子节点,左孩子,右孩子,双亲;

2、满二叉树、完全二叉树、线索二叉树;

3、二叉树的5个性质:二叉树五大特性

4、遍历:先序遍历(DLR),中序遍历(LDR),后序遍历(LRD);

5、常用操作:递归,返回指针、int;

6、用最简单的例子写算法,简单例子能用,复杂的就也能用

二、二叉树的遍历算法

1、节点存储结构:

struct binode
{
	char ch;
	binode* lchild;
	binode* rchild;
};

2、算法代码

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

#define ok 1
#define error -1

struct binode
{
	char ch;
	binode* lchild;
	binode* rchild;
};

binode* creatbitree(binode* t)  // 创建二叉树,以‘#’表示空指针;DLR遍历
{
	cout << "请输入字符:" << endl;
	char ch;
	cin >> ch;
	if (ch == '#')
	{
		return NULL;
	}
	t = new binode;   // DLR
	t->ch = ch;
	t->lchild = creatbitree(t->lchild);
	t->rchild = creatbitree(t->rchild);
	return t;
}

int previsit(binode* t) //前序遍历
{
	if (t == NULL)
	{
		return ok;
	}
	cout << t->ch;
	previsit(t->lchild);
	previsit(t->lchild);
	return ok;

}

int invisit(binode* t) //中序遍历
{
	if (t == NULL)
	{
		return ok;
	}
	
	invisit(t->lchild);
	cout << t->ch;
	invisit(t->lchild);
	return ok;

}

int backvisit(binode* t) //后序遍历
{
	if (t == NULL)
	{
		return ok;
	}

	backvisit(t->lchild);

	backvisit(t->lchild);
	cout << t->ch;
	return ok;

}
int levelvisit(binode* t) //层次遍历,用队列的概念
{
	if (t == NULL)
	{
		return 0;
	}
	else
	{
		queue<binode*> q;
		q.push(t);
		while (!q.empty())
		{
			if (q.front()->lchild != NULL)
			{
				q.push(q.front()->lchild);
			}
			if (q.front()->rchild != NULL)
			{
				q.push(q.front()->rchild);
			}
			cout << q.front()->ch;
			q.pop();
		}
		return ok;
	}
}

binode* copy(binode* t)  //dlr 拷贝算法
{
	if (t = NULL)
	{
		return NULL;
	}
	binode* c_t = new binode;
	c_t->ch = t->ch;
	c_t->lchild = copy(t->lchild);
	c_t->rchild = copy(t->rchild);
	return c_t;
}

int depth(binode* t)  // 求深度
{
	if (t == NULL)
	{
		return 0;
	} 
	int m = depth(t->lchild);    //左子树深度
	int n = depth(t->rchild);    //右子树深度
	if (m > n)
	{
		return m + 1;
	}
	else
	{
		return n + 1;
	}
}

int nodecount(binode* t)  //求节点总数,左加右加根
{
	if (t == NULL)
	{
		return 0;
	}
	return nodecount(t->lchild) + nodecount(t->rchild) + 1;
}

int leafcount(binode* t)   //求叶子节点
{
	if (t == NULL)
	{
		return 0;
	}
	if (t->lchild == NULL && t->rchild == NULL)
	{
		return 1;
	}
	return leafcount(t->lchild) + leafcount(t->rchild);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值