forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-all-the-lonely-nodes.cpp
60 lines (57 loc) · 1.57 KB
/
find-all-the-lonely-nodes.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
// Time: O(n)
// Space: O(h)
/**
* 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:
vector<int> getLonelyNodes(TreeNode* root) {
vector<int> result;
vector<TreeNode *> stk = {root};
while (!stk.empty()) {
auto node = stk.back(); stk.pop_back();
if (!node) {
continue;
}
if (node->left && !node->right) {
result.emplace_back(node->left->val);
} else if (node->right && !node->left) {
result.emplace_back(node->right->val);
}
stk.emplace_back(node->right);
stk.emplace_back(node->left);
}
return result;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
vector<int> getLonelyNodes(TreeNode* root) {
vector<int> result;
dfs(root, &result);
return result;
}
private:
void dfs(TreeNode *node, vector<int> *result) {
if (!node) {
return;
}
if (node->left && !node->right) {
result->emplace_back(node->left->val);
} else if (node->right && !node->left) {
result->emplace_back(node->right->val);
}
dfs(node->left, result);
dfs(node->right, result);
}
};