題目連結:二叉樹深度
思路
儲存二叉樹的各個節點並遞迴搜尋二叉樹深度。
題解
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int N = 1e5 + 10;
struct binary {
int lchild, rchild;
}tree[N];
// 遞迴搜尋
ll query(int now) {
if (tree[now].lchild == 0 && tree[now].rchild == 0) {
return 1;
}
ll res = query(tree[now].lchild);
res = max(res, query(tree[now].rchild));
return res + 1;
}
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
int l, r;
cin >> l >> r;
tree[i].lchild = l, tree[i].rchild = r;
}
cout << query(1) << endl;
return 0;
}