求二叉树的深度

// 树的高度.cpp : 定义控制台应用程序的入口点。
// 树的遍历.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <algorithm>
using namespace std;

struct BTNode{
	int data;
	struct BTNode *lchild, *rchild;
};
typedef struct BTNode  BTnode;
typedef struct BTNode* BiTree;

void preOrder(BTNode *root){
	if (root == NULL){
		return;
	}
	printf("%d",root->data);
	//遍历左子树
	preOrder(root->lchild);
	//遍历右子树
	preOrder(root->rchild);
}
void inOrder(BTNode *root){//中序遍历
	if (root == NULL){
		return;
	}
	//遍历左子树
	preOrder(root->lchild);
	printf("%d", root->data);
	//遍历右子树
	preOrder(root->rchild);
}
void postOrder(BTNode *root){//后序遍历
	if (root == NULL){
		return;
	}
	//遍历左子树
	preOrder(root->lchild);
	
	//遍历右子树
	preOrder(root->rchild);
	printf("%d", root->data);

}
//求树的深度
int Depth(BTNode *T){
	int depthleft = 0;
	int depthright = 0;
	int depthval = 0;
	if (T == NULL) return depthval;
	depthleft = Depth(T->lchild);
	depthright = Depth(T->rchild);
	depthval =1+ max(depthleft, depthright);
	return depthval;
}

int _tmain(int argc, _TCHAR* argv[])
{
	BTNode t1, t2, t3, t4, t5;
	memset(&t1,0,sizeof(BTNode));
	memset(&t2, 0, sizeof(BTNode));
	memset(&t3, 0, sizeof(BTNode));
	memset(&t4, 0, sizeof(BTNode));
	memset(&t5, 0, sizeof(BTNode));

	t1.data = 1;
	t2.data = 2;
	t3.data = 3;
	t4.data = 4;
	t5.data = 5;

	//建立关系
	t1.lchild = &t2;
	t1.rchild = &t3;
	t2.lchild = &t4;
	t3.lchild = &t5;
	
	//树的遍历
	cout << "先序遍历" << endl;
	preOrder(&t1);
	cout << "中序遍历" << endl;
	inOrder(&t1);
	cout << "后序遍历" << endl;
	postOrder(&t1);

	//求树的高度
	cout << "树的高度:"<<Depth(&t1) << endl;//3
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值