-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0104_max_depth.cc
48 lines (42 loc) · 996 Bytes
/
0104_max_depth.cc
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
/**
* Author: Xiangyue Cai
* Date: 2019-10-22
*/
// Example:
// Given 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) {
if (root == NULL) return 0;
stack<pair<int, TreeNode*>> s;
s.push({1, root});
int depth = 0;
int current_depth = 0;
while (!s.empty()) {
current_depth = s.top().first;
root = s.top().second;
s.pop();
if (root != NULL) {
depth = max(depth, current_depth);
s.push({current_depth + 1, root->left});
s.push({current_depth + 1, root->right});
}
}
return depth;
}
};