P4913 【深基16.例3】二叉树深度 【二叉树】

根据节点子节点信息构建二叉树,并计算其深度。输入包含二叉树的节点连接,输出为树的最大深度。示例中展示了含有7个节点的二叉树,其深度为4。

题目描述

给出每个节点的两个儿子节点,建立一棵二叉树(根节点为 111),如果是叶子节点,则输入0 0。建好树后希望知道这棵二叉树的深度。二叉树的深度是指从根节点到叶子结点时,最多经过了几层。

最多有 10610^6106 个结点。
输入格式


输出格式


输入输出样例
输入 #1

7
2 7
3 6
4 5
0 0
0 0
0 0
0 0

输出 #1

4

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

const int maxn = 1e6 + 10;
struct node{
	int l, r;
}tree[maxn];
int n, ans;

void search(int root, int deep) {
	if(tree[root].l == 0 && tree[root].r == 0) {
		ans = max(ans, deep);
		return;
	}
	if(tree[root].l != 0)	search(tree[root].l, deep + 1);
	if(tree[root].r != 0)	search(tree[root].r, deep + 1);
}

int main() {
	cin >> n;
	int x, y;
	for(int i = 1; i <= n; i++) {
		cin >> x >> y;
		tree[i].l = x;
		tree[i].r = y;
	}
	search(1, 1);
	cout << ans;
	return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值