P4913 【深基16.例3】二叉树深度
思路:动态建立二叉树,然后从头结点深度遍历,找到最大的深度
ac:
#include "iostream"
using std::cin;
using std::cout;
using std::endl;
int n,a,b,temp=1;
int max=0;
struct Tree{
int data;
struct Tree* lchild;
struct Tree* rchild;
};
void dfs(int x, Tree* T) {
if (T == NULL)
return;
if (T->data == x)
{
if (a != 0) {
Tree* q = new Tree;
q->data = a;
T->lchild = q;
q->lchild = NULL;
q->rchild = NULL;
}
else T->lchild = NULL;
if (b != 0) {
Tree* p = new Tree;
p->data = b;
T->rchild = p;
p->lchild = NULL;
p->rchild = NULL;
}
else T->rchild = NULL;
return;
}
dfs(x, T->lchild);
dfs(x, T->rchild);
}
void dfs2(Tree* T, int temp) {
if (T == NULL) {
if (temp - 1 > max)
{
max = temp - 1;
}
return;
if (temp - 1 > max) {
max = temp - 1;
}
}
dfs2(T->lchild, temp + 1);
dfs2(T->rchild, temp + 1);
}
int main() {
cin >> n;
Tree* root = new Tree;
root->data = 1;
cin >> a >> b;
if (a != 0) {
Tree* q = new Tree;
q->data = a;
root->lchild = q;
q->lchild = NULL;
q->rchild = NULL;
}
else root->lchild = NULL;
if (b != 0) {
Tree* p = new Tree;
p->data = b;
root->rchild = p;
p->lchild = NULL;
p->rchild = NULL;
}
else root->rchild = NULL;
for (int i = 1; i < n; i++) {
cin >> a >> b;
dfs(i + 1, root);
}
dfs2(root,temp);
cout << max;
}