数据结构-二叉树

h

#pragma once
#include "pch.h"
namespace tree {
 class treelist {
 public:
	 void douinit(treelist *&);//需要用二级指针 ,因为树是用形参的一级指针new  要用二级指针来保证new不被释放
	 void douwatchp(treelist *);//先序遍历
	 void douwatchc(treelist *);//中序
	 void douwatchb(treelist *);//后序
	 void douleaf(treelist *);//先序输出叶子节点
	 int  douleafcount(treelist *);//分治统计叶子数目
	 void higp(treelist *, int);//先序递归树的深度
	 void douinitthread(treelist *);//创建线索树
	 treelist *doucthreadp(treelist *);//中序线索树前驱
	 treelist *doucthreadb(treelist *);//中序线索树后驱
	 treelist *doucthreadp1(treelist *);//中序线索树第一个节点
	 treelist *douthreadcount(treelist *);//中序线索树遍历

 private:
		char data;
		treelist *ld;
		treelist *rd;
		int lcount = 0;//叶子数目
		int ldtag=0;//左驱
		int rdtag=0;//右驱
	};
}

cpp

#include "pch.h"
#include "树.h"
extern int hig;
tree::treelist *pre;
using namespace tree;
void tree::treelist::douinit(treelist *&l)
{
	char x; x = getchar();
	if (x == ' ')
	{
		l = NULL;
	}
	else {
		l = new treelist;
		l->data = x;
		douinit(l->ld);
		douinit(l->rd);
	}
};
void   treelist::douwatchp(treelist* l)
{
	if (l)
	{
		cout << l->data;
		douwatchp(l->ld);
		douwatchp(l->rd);
	}
};
void   treelist::douwatchc(treelist* l)
{
	if (l)
	{
		douwatchp(l->ld);
		cout << l->data << endl;
		douwatchp(l->rd);
	}
};
void   treelist::douwatchb(treelist* l)
{
	if (l)
	{
		douwatchp(l->ld);
		douwatchp(l->rd);
		cout << l->data << endl;
	}
};
void   treelist::douleaf(treelist* l)
{
	if (l)
	{
		if (l->ld == NULL && l->rd == NULL)
		{
			cout <<"节点是:"<< l->data << endl;
		}
		douwatchp(l->ld);
		douwatchp(l->rd);
	}
};
int treelist::douleafcount(treelist* l)
{
	if (l == NULL)
		l->lcount = 0;
	else if (l->ld == NULL && l->rd == NULL)
		l->lcount++;
	else
		l->lcount = douleafcount(l->ld) + douleafcount(l->rd);//对楼上的递归
	cout<< "叶节点总数是"<<l->lcount << endl;
	return l->lcount;
};
void treelist::higp(treelist*l, int h)//h是当前层
{
	if(l)
	{
		if (hig < h)
		{
			hig = h;
			higp(l->ld, h + 1);
			higp(l->rd, h + 1);
		}
    }
	cout<<"树的高度是"<<endl;
};
void  treelist::douinitthread(treelist *l)//0是孩子 1是前/后驱
{
	if (l)
	{
		douinitthread(l->ld);//1 左遍历
		if (l->ld = NULL)// 2左遍历完
		{
			l->ldtag = 1; l->ld = pre;// 3回到上个节点 如果右节点空跳4,否则6
		}
		if (pre->rd = NULL)//4
		{
			pre->rdtag = 1; pre->rd = l;//5右空指向上节点
		}
		pre = l;// 6继续往下访问
		douinitthread(l->rd);//右遍历继续 
	}
};
treelist *  treelist::doucthreadp(treelist *l)
{
	treelist *p;
	p = l->ld;
	if (l->ldtag!= 1)//左子不是前驱
	{
		while (p->rdtag == 0)//找第一个没有右子的节点
			p = p->rd;
	}
	return p;
};
treelist * treelist::doucthreadb(treelist *l)
{
	treelist *p;
	p = l->rd;
	if (l->rdtag != 1)
	{
		while (p->ldtag == 0)
			p = p->ld;
	}
	return p;
};
treelist * treelist::doucthreadp1(treelist *l)
{
	treelist *p=l;
	if (!p) return NULL;
	while (p->ldtag == 0)
		p = p->ld;
	return p;
};
treelist * treelist::douthreadcount(treelist *l)
{
	treelist *p = doucthreadp1(l);
	while (p)
	{
		cout << p->data;
		p = doucthreadb(p);
	}
	return p;
};


你可能感兴趣的:(数据结构)