|
37 | 37 |
|
38 | 38 | ## Solutions
|
39 | 39 |
|
40 |
| -### Solution 1 |
| 40 | +### Solution 1: BFS |
| 41 | + |
| 42 | +We can use Breadth-First Search, starting from the root node. When we reach node $u$, we return the next node in the queue. |
| 43 | + |
| 44 | +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. |
41 | 45 |
|
42 | 46 | <!-- tabs:start -->
|
43 | 47 |
|
@@ -121,9 +125,15 @@ public:
|
121 | 125 | for (int i = q.size(); i; --i) {
|
122 | 126 | root = q.front();
|
123 | 127 | q.pop();
|
124 |
| - if (root == u) return i > 1 ? q.front() : nullptr; |
125 |
| - if (root->left) q.push(root->left); |
126 |
| - if (root->right) q.push(root->right); |
| 128 | + if (root == u) { |
| 129 | + return i > 1 ? q.front() : nullptr; |
| 130 | + } |
| 131 | + if (root->left) { |
| 132 | + q.push(root->left); |
| 133 | + } |
| 134 | + if (root->right) { |
| 135 | + q.push(root->right); |
| 136 | + } |
127 | 137 | }
|
128 | 138 | }
|
129 | 139 | return nullptr;
|
@@ -200,7 +210,11 @@ var findNearestRightNode = function (root, u) {
|
200 | 210 |
|
201 | 211 | <!-- tabs:end -->
|
202 | 212 |
|
203 |
| -### Solution 2 |
| 213 | +### Solution 2: DFS |
| 214 | + |
| 215 | +DFS performs a pre-order traversal of the binary tree. The first time we search to node $u$, we mark the current depth $d$. The next time we encounter a node at the same level, it is the target node. |
| 216 | + |
| 217 | +The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes in the binary tree. |
204 | 218 |
|
205 | 219 | <!-- tabs:start -->
|
206 | 220 |
|
@@ -291,29 +305,27 @@ class Solution {
|
291 | 305 | */
|
292 | 306 | class Solution {
|
293 | 307 | public:
|
294 |
| - TreeNode* u; |
295 |
| - TreeNode* ans; |
296 |
| - int d = 0; |
297 |
| - |
298 | 308 | TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) {
|
299 |
| - this->u = u; |
| 309 | + TreeNode* ans; |
| 310 | + int d = 0; |
| 311 | + function<void(TreeNode*, int)> dfs = [&](TreeNode* root, int i) { |
| 312 | + if (!root || ans) { |
| 313 | + return; |
| 314 | + } |
| 315 | + if (d == i) { |
| 316 | + ans = root; |
| 317 | + return; |
| 318 | + } |
| 319 | + if (root == u) { |
| 320 | + d = i; |
| 321 | + return; |
| 322 | + } |
| 323 | + dfs(root->left, i + 1); |
| 324 | + dfs(root->right, i + 1); |
| 325 | + }; |
300 | 326 | dfs(root, 1);
|
301 | 327 | return ans;
|
302 | 328 | }
|
303 |
| - |
304 |
| - void dfs(TreeNode* root, int i) { |
305 |
| - if (!root || ans) return; |
306 |
| - if (d == i) { |
307 |
| - ans = root; |
308 |
| - return; |
309 |
| - } |
310 |
| - if (root == u) { |
311 |
| - d = i; |
312 |
| - return; |
313 |
| - } |
314 |
| - dfs(root->left, i + 1); |
315 |
| - dfs(root->right, i + 1); |
316 |
| - } |
317 | 329 | };
|
318 | 330 | ```
|
319 | 331 |
|
|
0 commit comments