题目描述
给出每个节点的两个儿子节点,建立一棵二叉树(根节点为 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;
}
根据节点子节点信息构建二叉树,并计算其深度。输入包含二叉树的节点连接,输出为树的最大深度。示例中展示了含有7个节点的二叉树,其深度为4。
3110

被折叠的 条评论
为什么被折叠?



