Java 为什么要检查n.parent==null?

Java 为什么要检查n.parent==null?,java,graph,tree,Java,Graph,Tree,我在二叉搜索树中查找给定节点的“下一个”节点(即顺序继承节点) 为什么在下面给出的代码中使用此条件: 如果(n.parent==null | | n.right!=null) 我的问题是:为什么要检查n.parent==null? 完整代码: public static TreeNode inorderSucc(TreeNode n) { if (n == null) return null; // Found right children -> return le

我在二叉搜索树中查找给定节点的“下一个”节点(即顺序继承节点)

为什么在下面给出的代码中使用此条件:

  • 如果(n.parent==null | | n.right!=null)
我的问题是:为什么要检查n.parent==null?

完整代码:

public static TreeNode inorderSucc(TreeNode n) { 
    if (n == null) return null;

    // Found right children -> return left most node of right subtree
    if (n.parent == null || n.right != null) { 
        return leftMostChild(n.right); 
    } else { 
        TreeNode q = n;
        TreeNode x = q.parent;
        // Go up until we’re on left instead of right
        while (x != null && x.left != q) {
            q = x;
            x = x.parent;
        }
        return x;
    }  
} 

public static TreeNode leftMostChild(TreeNode n) {
    if (n == null) {
        return null;
    }
    while (n.left != null) {
        n = n.left; 
    }
    return n; 
}

检查
n
是否是根节点,并且它有一个右子树。

如果您触摸的第一个节点(BST的中间节点)是您需要的唯一节点,该怎么办?e、 在二叉树中进行搜索,初始节点包含要查找的值。我想现在我找到了。谢谢
if (n.parent == null || n.right != null)