我发现了下一个'二叉搜索树中给定节点的节点(即,有序后继)。
为什么在下面给出的代码中使用了这个条件:
我的问题是:我们为什么要检查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;
}
答案 0 :(得分:3)
if (n.parent == null || n.right != null)
检查n
是否为 root 节点,并且它具有正确的子树。