forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0104-maximum-depth-of-binary-tree.cpp
56 lines (52 loc) · 1.47 KB
/
0104-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
/*
Given root of binary tree, return max depth (# nodes along longest path from root to leaf)
At every node, max depth is the max depth between its left & right children + 1
Time: O(n)
Space: O(n)
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
// class Solution {
// public:
// int maxDepth(TreeNode* root) {
// if (root == NULL) {
// return 0;
// }
// queue<TreeNode*> q;
// q.push(root);
// int result = 0;
// while (!q.empty()) {
// int count = q.size();
// for (int i = 0; i < count; i++) {
// TreeNode* node = q.front();
// q.pop();
// if (node->left != NULL) {
// q.push(node->left);
// }
// if (node->right != NULL) {
// q.push(node->right);
// }
// }
// result++;
// }
// return result;
// }
// };