-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathHeightOfBinaryTree.c
69 lines (58 loc) · 1.2 KB
/
HeightOfBinaryTree.c
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
// Output Format
// Output one integer that is the height of the binary search tree.
// Sample Input 0
// 10
// 2 8 5 1 10 5 9 9 3 5
// Sample Output 0
// 6
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
struct TreeNode{
int x;
struct TreeNode* L;
struct TreeNode* R;
};
typedef struct TreeNode TreeNode;
TreeNode* newNode(int y){
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->x = y;
node->L = node->R = NULL;
return node;
}
int height(TreeNode *root){
if(root==NULL)
return 0;
else{
int ldepth = height(root->L);
int rdepth = height(root->R);
if(ldepth>rdepth)
{
return ldepth+1;
}
else
return rdepth+1;
}
}
TreeNode* insert(TreeNode* node, int val)
{
if(node==NULL) return newNode(val);
if(val<=node->x){
node->L = insert(node->L, val);
}else{
node->R = insert(node->R, val);
}
return node;
}
int main() {
int val, N;
scanf("%d", &N);
TreeNode* Root= NULL;
for(int i=1;i<=N; i++){
scanf("%d", &val);
Root = insert(Root, val);
}
printf("%d", height(Root));
return 0;
}