简单的DFS,用数组w记录每一层的宽度就行了,就是遇到一层就++。中间发现在C++里面,如果int未初始化就是用也是有异常的。还有二叉树的数组表示时,从1开始计数会比较好。还有后来学会了数组这样的初始化为0的方法:int l[100] = {0},r[100] = {0};
#include <iostream> using namespace std; int l[20]; int r[20]; int w[20]; int dfs(int level, int node) { w[level]++; if (l[node] == 0 && r[node] == 0) return 1; int dl = 0; int dr = 0; if (l[node] != 0) { dl = dfs(level+1, l[node]); } if (r[node] != 0) { dr = dfs(level+1, r[node]); } int max = dl > dr ? dl : dr; return max+1; } int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { cin >> l[i] >> r[i]; } int dmax = dfs(1, 1); int wmax = 0; for (int i = 0; i <= dmax; i++) { if (w[i] > wmax) wmax = w[i]; } cout << wmax << " " << dmax; }