如果有一个节点有 个子节点,那么这棵树肯定不是二叉树,否则的话直接深搜求每个点的深度即可。
#include <bits/stdc++.h>
using namespace std ;
long long n , l[100005] , r[100005] , maxn ;
void dfs(long long x , long long step) {
maxn = max(maxn , step) ;
if(l[x]) {
dfs(l[x] , step + 1) ;
}
if(r[x]) {
dfs(r[x] , step + 1) ;
}
}
int main() {
cin >> n ;
for(int i = 2 , x ; i <= n ; i ++) {
cin >> x ;
if(l[x] == 0) {
l[x] = i ;
} else if(r[x] == 0) {
r[x] = i ;
} else {
cout << "No" ;
return 0 ;
}
}
dfs(1 , 1) ;
cout << maxn ;
return 0 ;
}
- 时间复杂度: 。
- 空间复杂度: 。
暂无评论