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

时间:2015-04-08 06:17:48

标签: java graph tree

我发现了下一个'二叉搜索树中给定节点的节点(即,有序后继)。

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

  • if(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; 
}

1 个答案:

答案 0 :(得分:3)

if (n.parent == null || n.right != null)

检查n是否为 root 节点,并且它具有正确的子树。