Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1663c26

Browse files
Depth of binary tree
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent aab7f22 commit 1663c26

File tree

4 files changed

+60
-0
lines changed

4 files changed

+60
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test bst_depth.c
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct TreeNode {
5+
int val;
6+
struct TreeNode *left;
7+
struct TreeNode *right;
8+
};
9+
10+
static int maxDepth(struct TreeNode* root)
11+
{
12+
if (root == NULL) {
13+
return 0;
14+
}
15+
int l = maxDepth(root->left) + 1;
16+
int r = maxDepth(root->right) + 1;
17+
return l > r ? l : r;
18+
}
19+
20+
int main(void)
21+
{
22+
printf("%d\n", maxDepth(NULL));
23+
return 0;
24+
}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test bst_depth.c
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct TreeNode {
5+
int val;
6+
struct TreeNode *left;
7+
struct TreeNode *right;
8+
};
9+
10+
static int minDepth(struct TreeNode* root)
11+
{
12+
if (root == NULL) {
13+
return 0;
14+
}
15+
16+
int l = minDepth(root->left) + 1;
17+
int r = minDepth(root->right) + 1;
18+
return l < r ? (l > 1 ? l : r) : (r > 1 ? r : l);
19+
}
20+
21+
int main(void)
22+
{
23+
struct TreeNode root, n1;
24+
root.val = 1;
25+
n1.val = 2;
26+
root.left = &n1;
27+
root.right = NULL;
28+
n1.left = NULL;
29+
n1.right = NULL;
30+
printf("%d\n", minDepth(&root));
31+
return 0;
32+
}

0 commit comments

Comments
 (0)