其他分享
首页 > 其他分享> > 计算树的结点,树的子叶,树的深度,复制树

计算树的结点,树的子叶,树的深度,复制树

作者:互联网

计算树的结点和树的子叶三种遍历顺序都可以,计算树的深度和树的复制考虑后序遍历的顺序

#include <stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef char TElemtype;

typedef struct BiTNode
{
	TElemtype Data;
	struct BiTNode* Lchild, * Rchild;

}BiTNode;
typedef BiTNode* BiTree;
  int count;
void CountNode(BiTree Tree)
{
	if (Tree) {
		count++;
		CountNode(Tree->Lchild);
		CountNode(Tree->Rchild);
	}
}

void CountLeaves(BiTree Tree)
{
	if (Tree)
	{
		if (!Tree->Lchild && !Tree->Lchild)count++;
		CountLeaves(Tree->Lchild);
		CountLeaves(Tree->Rchild);
	}
}

int Depth(BiTree Tree)
{
	if (!Tree) return 0;
	int Lhigh = 0, Rhigh = 0;
	Lhigh = Depth(Tree->Lchild);
	Rhigh = Depth(Tree->Rchild);
	int High = (Lhigh > Rhigh ? Lhigh : Rhigh) + 1;
	return High;
}

BiTree CreateNode(TElemtype e, BiTree L, BiTree R)
{
	BiTree T;
	T = (BiTree)malloc(sizeof(BiTNode));
	if (!T) exit(1);
	T->Data = e;
	T->Lchild = L;
	T->Rchild = R;
}

BiTree CopyTree(BiTree Tree)
{
	BiTree NewLeft, NewRight;
	if (!Tree) return NULL;
	if (Tree->Lchild) NewLeft = CopyTree(Tree->Lchild);
	else NewLeft = NULL;
	if (Tree->Rchild) NewRight = CopyTree(Tree->Rchild);
	else NewRight = NULL;
	BiTree NewTree = CreateNode(Tree->Data, NewLeft, NewRight);
	return NewTree;
}

标签:Lchild,结点,子叶,int,BiTree,Tree,BiTNode,复制,Rchild
来源: https://www.cnblogs.com/tzp-empty-hya/p/14645416.html