求这棵树的高度

46 篇文章 0 订阅
37 篇文章 3 订阅
题目描述

一棵树有n个节点,其中1号节点为根节点。

输入格式

第一行是整数n,表示节点数
后面若干行,每行两个整数a b,表示b是a的子节点。

输出

求这棵树的高度(根节点为第1层)

样例输入
5
1 2
1 3
3 4
3 5
样例输出

3



#include<iostream>

using namespace std;

struct Node
{
	int data;
	Node *left;
	Node *right;
};

int left_height = 0;
int right_height = 0;


Node *Tree_Insert(Node *T, int parent, int child)
{
	Node *temp1 = T, *temp2;
	if(temp1 == NULL)
		return T;
	//
	if(temp1->data == parent)
	{
		temp2 = new Node;
		temp2->data = child;
		temp2->left = NULL;
		temp2->right = NULL;
		if(temp1->left == NULL)
		{
			temp1->left = temp2;
		}	
		else
		{
			temp1->right = temp2;
		}
		return T;
	}
	Tree_Insert(T->left, parent, child);
	Tree_Insert(T->right, parent, child);

	return T;
}

int leftheight = 0;
int rightheight = 0;


int Tree_CengNum(Node *T)
{
	if(T == NULL)
		return 0;
	if(T->left)
	{
		leftheight++;
		Tree_CengNum(T->left) + 1;
	}
	if(T->right)
	{
		rightheight++;
		Tree_CengNum(T->left) + 1;
	}
	return (leftheight > rightheight) ? (leftheight + 1) : (rightheight);
}

Node *Creat()
{
	int n;
	Node *T = NULL;
	cin>>n;
	while(n > 1)
	{
		int a, b;
		cin>>a>>b;
		T = new Node;
		T->data = a;
		T->left = NULL;
		T->right = NULL;

		T = Tree_Insert(T, a, b);
		//
		n--;
	}
	return T;
	
}


void main()
{
	Node *T = Creat();
	cout<<Tree_CengNum(T) + 1 <<endl;
	system("pause");
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值