给定一棵二叉树的根节点 root
和树中的一个节点 u
,返回与 u
所在层中距离最近的右侧节点,当 u
是所在层中最右侧的节点,返回 null
。
示例 1:
输入:root = [1,2,3,null,4,5,6], u = 4 输出:5 解释:节点 4 所在层中,最近的右侧节点是节点 5。
示例 2:
输入:root = [3,null,4,2], u = 2 输出:null 解释:2 的右侧没有节点。
示例 3:
输入:root = [1], u = 1 输出:null
示例 4:
输入:root = [3,4,2,null,null,null,1], u = 4 输出:2
提示:
- 树中节点个数的范围是
[1, 105]
。 1 <= Node.val <= 105
- 树中所有节点的值是唯一的。
u
是以root
为根的二叉树的一个节点。
BFS 层序遍历。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> TreeNode:
q = deque([root])
while q:
n = len(q)
for i in range(n):
node = q.popleft()
if node == u:
return None if i == n - 1 else q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode findNearestRightNode(TreeNode root, TreeNode u) {
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
for (int i = 0, n = q.size(); i < n; ++i) {
TreeNode node = q.poll();
if (node == u) {
return i == n - 1 ? null : q.poll();
}
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
}
}
return null;
}
}
/**
* 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:
TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty())
{
for (int i = 0, n = q.size(); i < n; ++i)
{
TreeNode* node = q.front();
q.pop();
if (node == u) return i == n - 1 ? nullptr : q.front();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return nullptr;
}
};
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func findNearestRightNode(root *TreeNode, u *TreeNode) *TreeNode {
q := []*TreeNode{root}
for len(q) > 0 {
t := q
q = nil
for i, node := range t {
if node == u {
if i == len(t)-1 {
return nil
}
return t[i+1]
}
if node.Left != nil {
q = append(q, node.Left)
}
if node.Right != nil {
q = append(q, node.Right)
}
}
}
return nil
}