题目描述:给出每个节点的两个儿子节点,建立一棵二叉树,如果是叶子节点,则输入0 0
。建好树后希望知道这棵二叉树的深度。二叉树的深度是指从根节点到叶子结点时,最多经过了几层。
最多有 10^6 个结点。
输入:
7 2 7 3 6 4 5 0 0 0 0 0 0 0 0
输出:
4
分析:给你一颗树,求它的最大深度,第一反应就是dfs,但是一看数据量10^6次直接就被劝退了,转而想写bfs,我个人认为,在类似于跑最大深度的问题上,bfs要比dfs效率高(蒟蒻理解),因为dfs要不断回溯,
所以效率不高,bfs按层序遍历,效率较高,由于本人水平有限,没有用手写队列,用了std.
#include<bits/stdc++.h> using namespace std; struct node { int left=-1; int right=-1;//用-1来表示无节点,和0区别开 int step; } e[100005]; int n; int total; queue<node> q; void bfs(int i) { node a; a.left=e[i].left; a.right=e[i].right; a.step=1; q.push(a); while(!q.empty()) { node c=q.front(); q.pop(); int x=c.left; int y=c.right; int z=c.step; total=max(z,total); if(x==-1) continue; if(y==-1) continue; if(x!=0) { node b; b.left=e[x].left; b.right=e[x].right; b.step=z+1;//这里不能z++ q.push(b); } if(y!=0) { node b; b.left=e[y].left; b.right=e[y].right; b.step=z+1; q.push(b); } } } int main() { cin>>n; for(int i=1; i<=n; i++) { int x,y; cin>>x>>y; e[i].left=x; e[i].right=y; } bfs(1); cout<<total; return 0; }