[LeetCode] Find Nearest Right Node in Binary Tree

1602. Find Nearest Right Node in Binary Tree

Given the root of a binary tree and a node u in the tree, return the nearest node on the same level that is to the right of u, or return null if u is the rightmost node in its level.

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
/**
* 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 {
bool find = false;
int targetLevel = -1;
public:
TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u, bool moveRight = false, int level = 0) {
if(!root) return nullptr;

if(find) {
if(level == targetLevel) return root;
if(moveRight) {
auto res = findNearestRightNode(root->left, u, moveRight, level + 1);
if(res) return res;
}
return findNearestRightNode(root->right, u, true, level + 1);
}
if(root == u) {
find = true;
targetLevel = level;
return nullptr;
}

auto res = findNearestRightNode(root->left, u, false, level + 1);
if(find and res != nullptr) {
return res;
}

return findNearestRightNode(root->right, u, find, level + 1);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/07/PS/LeetCode/find-nearest-right-node-in-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.