-
Notifications
You must be signed in to change notification settings - Fork 0
/
104.maximum-depth-of-binary-tree.cpp
141 lines (134 loc) · 3.33 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/**
* 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:
// version 1 : dfs recursive version
/*
int maxDepth(TreeNode* root) {
if (!root) {
return 0;
}
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
// return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;
}
*/
// version 2 : dfs non-recursive version
/*
int maxDepth(TreeNode* root) {
int res = 0;
if (!root) {
return res;
}
stack<TreeNode*> s;
stack<int> sd;
TreeNode* node = root;
int depth = 1;
while (!s.empty() || node) {
if (node){
s.push(node);
sd.push(depth + 1);
node = node->left;
depth = sd.top();
} else {
node = s.top()->right;
depth = sd.top();
s.pop();
sd.pop();
}
res = max(res, depth);
}
return res - 1;
}
*/
// version 3 : dfs non-recursive version 2
/*
int maxDepth(TreeNode* root) {
int res = 0;
if (!root) {
return res;
}
stack<TreeNode*> s;
stack<int> sd;
s.push(root);
sd.push(1);
while (!s.empty()) {
TreeNode* node = s.top();
int depth = sd.top();
s.pop();
sd.pop();
res = max(res, depth);
if (node->left) {
s.push(node->left);
sd.push(depth + 1);
}
if (node->right) {
s.push(node->right);
sd.push(depth + 1);
}
}
return res;
}
*/
// version 3 : bfs non-recursive version 1 marker NULL
/*
int maxDepth(TreeNode* root) {
int res = 0;
if (!root) {
return res;
}
queue<TreeNode*> q;
q.push(root);
q.push(NULL);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (!node) {
res++;
if (!q.empty()) {
q.push(NULL);
}
} else {
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
}
return res;
}
*/
// version 4 : bfs non-recursive version 2 for loop
int maxDepth(TreeNode* root) {
int res = 0;
if (!root) {
return res;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front();
int qs = q.size();
for (int i = 0; i < qs; i++) {
node = q.front();
q.pop();
if (node->left) {
q.push(node->left);
}
if (node->right) {
q.push(node->right);
}
}
res++;
}
return res;
}
};