LeetCode 1602: Find Nearest Right Node in Binary Tree Solution
Master LeetCode problem 1602 (Find Nearest Right Node in Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1602. Find Nearest Right Node in Binary Tree
Problem Explanation
Explanation
Given a binary tree and a node u, we need to find the nearest node on the right side of u. We can perform a level order traversal of the tree and look for the first occurrence of u in each level. If u is found in a level, then the nearest right node will be the next node encountered in that level.
Algorithm:
- Perform a level order traversal of the binary tree.
- For each level, check if the current node is equal to the given node
u. - If
uis found in the level, return the next node encountered in that level. - If
uis the last node in its level, return null.
Time Complexity: O(N) where N is the number of nodes in the tree. Space Complexity: O(N) for the queue used in level order traversal.
Solution Code
class Solution {
public TreeNode findNearestRightNode(TreeNode root, TreeNode u) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
boolean found = false;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (found) return node;
if (node == u) found = true;
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
}
return null;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1602 (Find Nearest Right Node in Binary Tree)?
This page provides optimized solutions for LeetCode problem 1602 (Find Nearest Right Node in Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1602 (Find Nearest Right Node in Binary Tree)?
The time complexity for LeetCode 1602 (Find Nearest Right Node in Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1602 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1602 in Java, C++, or Python.