Skip to content

Commit fa58943

Browse files
authored
Create find-nearest-right-node-in-binary-tree.cpp
1 parent c671a58 commit fa58943

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(w)
3+
4+
class Solution {
5+
public:
6+
TreeNode* findNeartestRightNode(TreeNode* root, TreeNode* u) {
7+
vector<TreeNode *> q = {root};
8+
while (!empty(q)) {
9+
vector<TreeNode *> new_q;
10+
for (int i = 0; i < size(q); ++i) {
11+
if (q[i] == u) {
12+
return i + 1 < size(q) ? q[i + 1] : nullptr;
13+
}
14+
if (q[i]->left) {
15+
new_q.emplace_back(q[i]->left);
16+
}
17+
if (q[i]->right) {
18+
new_q.emplace_back(q[i]->right);
19+
}
20+
}
21+
q = move(new_q);
22+
}
23+
return nullptr;
24+
}
25+
};

0 commit comments

Comments
 (0)