-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104_Maximum_Depth_of_Binary_Tree.cpp
59 lines (50 loc) · 1.21 KB
/
104_Maximum_Depth_of_Binary_Tree.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
/*
104. Maximum Depth of Binary Tree
Description:
Given a binary tree,find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given a binary tree [3,9,20,null,null,15,7].
3
/ \
9 20
/ \
15 7
return its depth = 3.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int l1, l2, l;
l = l1 = l2 = 1;
if ( !root ) return 0;
if ( root->left ) { l1 = maxDepth(root->left) + 1;}
if ( root->right ) { l2 = maxDepth(root->right) + 1;}
l = (l1 > l2) ? l1 : l2;
return l;
}
};
// another way
class Solution {
public:
int maxDepth(TreeNode* root) {
int layer = 0;
if ( root != NULL ) {
layer++;
int layer_l = maxDepth(root->left);
int layer_r = maxDepth(root->right);
layer += (layer_l > layer_r) ? layer_l : layer_r;
}
return layer;
}
};