题目
设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例 1:
输入: root = [2,1,3], p = 1
2
/
1 3
输出: 2
示例 2:
输入: root = [5,3,6,2,4,null,null,1], p = 6
5
/
3 6
/
2 4
/
1
输出: null
代码
package dayLeetCode;
public class dayleetcode0406 {
public TreeNode0406 inorderSuccessor(TreeNode0406 root, TreeNode0406 p) {
if (root == null){
return null;
}
if (root.val <= p.val){
return inorderSuccessor(root.right, p);
}
TreeNode0406 node = inorderSuccessor(root.left, p);
return node == null ? root : node;
}
}
class TreeNode0406 {
int val;
TreeNode0406 left;
TreeNode0406 right;
TreeNode0406(int x) {
val = x;
}
}
二叉搜索树中寻找中序后继节点的算法实现
这篇博客介绍了如何设计一个算法来找到二叉搜索树中指定节点的中序后继节点。给出了示例输入和输出,并提供了相应的Java代码实现。当指定节点没有后继节点时,返回null。该算法通过递归地在右子树和左子树中查找来确定后继节点。
817

被折叠的 条评论
为什么被折叠?



