• [LeetCode] 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.

    Example 1:

    Input: root = [1,2,3,null,4,5,6], u = 4
    Output: 5
    Explanation: The nearest node on the same level to the right of node 4 is node 5.
    

    Example 2:

    Input: root = [3,null,4,2], u = 2
    Output: null
    Explanation: There are no nodes to the right of 2.
    

    Example 3:

    Input: root = [1], u = 1
    Output: null
    

    Example 4:

    Input: root = [3,4,2,null,null,null,1], u = 4
    Output: 2
    

    Constraints:

    • The number of nodes in the tree is in the range [1, 105].
    • 1 <= Node.val <= 105
    • All values in the tree are distinct.
    • u is a node in the binary tree rooted at root.

    找到二叉树中最近的右侧节点。

    题目很简单,就是常规的BFS,唯一需要注意的是如果在当前层存在u节点的话,需要判断u节点是否是当前层从左往右的最后一个节点,如果不是,他才会有右侧节点。

    时间O(n)

    空间O(n)

    Java实现

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode() {}
     8  *     TreeNode(int val) { this.val = val; }
     9  *     TreeNode(int val, TreeNode left, TreeNode right) {
    10  *         this.val = val;
    11  *         this.left = left;
    12  *         this.right = right;
    13  *     }
    14  * }
    15  */
    16 class Solution {
    17     public TreeNode findNearestRightNode(TreeNode root, TreeNode u) {
    18         Queue<TreeNode> queue = new LinkedList<>();
    19         queue.offer(root);
    20         while (!queue.isEmpty()) {
    21             int size = queue.size();
    22             for (int i = 0; i < size; i++) {
    23                 TreeNode cur = queue.poll();
    24                 if (cur.val == u.val) {
    25                     if (i < size - 1) {
    26                         return queue.poll();
    27                     } else {
    28                         return null;
    29                     }
    30                 }
    31                 if (cur.left != null) {
    32                     queue.offer(cur.left);
    33                 }
    34                 if (cur.right != null) {
    35                     queue.offer(cur.right);
    36                 }
    37             }
    38         }
    39         return null;
    40     }
    41 }

    LeetCode 题目总结

  • 相关阅读:
    .IllegalArgumentException: Mapped Statements collection does not contain 异常一例【我】
    Spring配置文件里加载路径中的通配符
    线程池使用Callable示例【我】
    使用Callable和Future接口创建线程
    Java线程池(Callable+Future模式)
    集合切割
    draw call 理解和优化
    Unity 3d导入3dMax模型 产生若干问题
    3dmax做的模型导入U3d后 当模型靠近摄像机时镂空问题
    不管多少个空格替换为一个空格
  • 原文地址:https://www.cnblogs.com/cnoodle/p/14176527.html
Copyright © 2020-2023  润新知