-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104.maximum-depth-of-binary-tree-top-down.c
More file actions
66 lines (54 loc) · 1.64 KB
/
Copy path104.maximum-depth-of-binary-tree-top-down.c
File metadata and controls
66 lines (54 loc) · 1.64 KB
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
#include <stdlib.h>
#include <stdio.h>
/**
* Definition for a binary tree node.
*/
struct TreeNode
{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
#define MAX(a, b) ((a) > (b) ? (a) : (b))
void maxDepthHelper(struct TreeNode *root, int level, int *depth)
{
if (root == NULL)
{
return;
}
*depth = MAX(level, *depth);
maxDepthHelper(root->left, level + 1, depth);
maxDepthHelper(root->right, level + 1, depth);
}
int maxDepth(struct TreeNode *root)
{
int depth = 0;
if (root == NULL)
return depth;
maxDepthHelper(root, 0, &depth);
return depth + 1;
}
int main(int argc, char const *argv[])
{
struct TreeNode *rootRightLeftRight = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightLeftRight->val = 4;
rootRightLeftRight->left = rootRightLeftRight->right = NULL;
struct TreeNode *rootRightLeftLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightLeftLeft->val = 5;
rootRightLeftLeft->left = rootRightLeftLeft->right = NULL;
struct TreeNode *rootRightLeft = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRightLeft->val = 3;
rootRightLeft->left = rootRightLeftLeft;
rootRightLeft->right = rootRightLeftRight;
struct TreeNode *rootRight = (struct TreeNode *)malloc(sizeof(struct TreeNode));
rootRight->val = 2;
rootRight->left = rootRightLeft;
rootRight->right = NULL;
struct TreeNode *root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 1;
root->left = NULL;
root->right = rootRight;
int depth = maxDepth(root);
printf("%d\n", depth);
return 0;
}