forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
height-of-special-binary-tree.cpp
47 lines (45 loc) · 1.18 KB
/
height-of-special-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
// Time: O(n)
// Space: O(h)
// dfs
class Solution {
public:
int heightOfTree(TreeNode* root) {
int result = -1;
vector<pair<TreeNode *, int>> stk = {{root, 0}};
while (!empty(stk)) {
const auto [u, d] = stk.back(); stk.pop_back();
result = max(result, d);
if (u->right && u->right->left != u) {
stk.emplace_back(u->right, d + 1);
}
if (u->left && u->left->right != u) {
stk.emplace_back(u->left, d + 1);
}
}
return result;
}
};
// Time: O(n)
// Space: O(w)
// bfs
class Solution2 {
public:
int heightOfTree(TreeNode* root) {
int result = -1;
vector<TreeNode *> q = {root};
while (!empty(q)) {
vector<TreeNode *> new_q;
for (const auto& u : q) {
if (u->left && u->left->right != u) {
new_q.emplace_back(u->left);
}
if (u->right && u->right->left != u) {
new_q.emplace_back(u->right);
}
}
q = move(new_q);
++result;
}
return result;
}
};