-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path39_1_TreeDepth.cpp
71 lines (60 loc) · 1.04 KB
/
39_1_TreeDepth.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <cstdio>
using namespace std;
#define MAX 12
struct BinaryTree
{
BinaryTree *left;
BinaryTree *right;
};
void CreateTree(BinaryTree **root, int n)
{
if (n <= 0)
return ;
BinaryTree* arr[MAX];
for (int i = 0;i < n;i ++)
{
arr[i] = new BinaryTree;
arr[i]->left = NULL;
arr[i]->right = NULL;
}
int left, right;
for (int i = 0;i < n; i++)
{
cin >> left >> right;
if (left != -1)
arr[i]->left = arr[left - 1];
if (right != -1)
arr[i]->right = arr[right - 1];
}
*root = arr[0];
}
void DeleteTree(BinaryTree **root)
{
if ((*root) == NULL)
return ;
DeleteTree(&((*root)->left));
DeleteTree(&((*root)->right));
delete *root;
}
int MaxDepth(BinaryTree *root)
{
if(root == NULL)
return 0;
int left = MaxDepth(root->left);
int right = MaxDepth(root->right);
return left >= right ? left + 1 : right + 1;
}
int main(void)
{
int n;
while (cin >> n)
{
BinaryTree *root = NULL;
CreateTree(&root, n);
int depth = MaxDepth(root);
cout << depth << endl;
DeleteTree(&root);
}
return 0;
}