二叉树常用基本操作

Posted 阳光Cherry梦

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树常用基本操作相关的知识,希望对你有一定的参考价值。

#include<iostream>
using namespace std;
/*
测试使用二叉树使用先序遍历输入字符串为ABC##DE#G##F###
*/
typedef char ElemType;
typedef struct BiTNode {
	ElemType data;
	struct BiTNode *lchild;
	struct BiTNode *rchild;
} BiTNode, *BiTree;

void CreateTree(BiTree &T) { //先序创建二叉树
	char c;
	cin>>c;
	if(c == '#') {
		T = NULL;
	} else {
		T = new BiTNode;//此处只能声明结点类型,对应指针
		T->data = c;
		CreateTree(T->lchild);
		CreateTree(T->rchild);
	}
}

void Pre(BiTree T) {//前序遍历
	if(T == NULL) return;
	else {
		cout<<T->data;
		Pre(T->lchild);
		Pre(T->rchild);
	}
}
void Middle(BiTree T) { //中序遍历
	if(T) return;
	else {
		Pre(T->lchild);
		cout<<T->data;
		Pre(T->rchild);
	}
}
void Post(BiTree T) { //后序遍历
	if(T) return;
	else {
		Pre(T->lchild);
		Pre(T->rchild);
		cout<<T->data;
	}
}

int NodeCount(BiTree T) {//节点个数
	if(T == NULL) return 0;
	else {
		return 1 + NodeCount(T->lchild) + NodeCount(T->rchild);
	}
}

int Depth(BiTree T) {//二叉树深度
	int m, n;
	if(T == NULL) return 0;
	else {
		m = Depth(T->lchild);
		n = Depth(T->rchild);
		if(m >= n) return m + 1;
		else return n + 1;
	}
}

int Node0(BiTree T) {
	if(T==NULL) return 0;
	else if((T->lchild == NULL) && (T->rchild==NULL)) {
		cout<<T->data;
		return 1;
	} else return Node0(T->lchild) + Node0(T->rchild);
}

int Node1(BiTree T) {
	if(T==NULL) return 0; //空树
	else if((T->lchild != NULL) && (T->rchild == NULL)) { //度为1,有左分支
		cout<<T->data;
		return 1 + Node1(T->lchild);
	} else if((T->lchild == NULL) && (T->rchild != NULL)) { //度为1,有右分支
		cout<<T->data;
		return 1 + Node1(T->rchild);
	} else if((T->lchild != NULL) && T->rchild != NULL)
		Node1(T->lchild) + Node1(T->rchild); //度为2
	else return 0;//度为0
}


int Node2(BiTree T) {
	if(T==NULL) return 0;//空树
	else if((T->lchild) && (T->rchild)) { //度为2
		cout<<T->data;
		return 1 + Node2(T->lchild) + Node2(T->rchild);
	}
}

void Copy(BiTree T, BiTree &NewT) {
	if(T == NULL) {
		NewT = NULL;
	} else {
		NewT = new BiTNode;
		NewT->data = T->data;
		Copy(T->lchild, NewT->lchild);
		Copy(T->rchild, NewT->rchild);
	}
}
int main() {
	cout<<"请输入创建字符串"<<endl;
	BiTree T;
	CreateTree(T);
	cout<<"先序输出二叉树结果"<<endl;
	Pre(T);
	cout<<endl;
	cout<<"结点个数:"<<NodeCount(T)<<endl;
	cout<<"树的深度:"<<Depth(T)<<endl;
	cout<<"叶子结点个数:"<<Node0(T)<<endl;
	cout<<"度为1的结点个数:"<<Node1(T)<<endl;
	cout<<"度为2的结点个数:"<<Node2(T)<<endl;
	BiTree NewT;
	Copy(T, NewT);
	Pre(NewT);
	return 0;
}

 

以上是关于二叉树常用基本操作的主要内容,如果未能解决你的问题,请参考以下文章

二叉树常用基本操作

二叉树常用基本操作

1 数据结构(13)_二叉树的概念及常用操作实现

数据结构 树与二叉树的基本概念结构特点及性质

二叉树的基本操作实现

常用数据结构——二叉树(还有三叉四叉...? )