标签:Node Nearest Right TreeNode val queue right null root
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 atroot
.
找到二叉树中最近的右侧节点。
题目很简单,就是常规的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 }
标签:Node,Nearest,Right,TreeNode,val,queue,right,null,root 来源: https://www.cnblogs.com/cnoodle/p/14176527.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。