BST:分析给定参考发现之前

时间:2018-05-27 04:47:22

标签: java binary-search-tree

我正在查看代码,以便在BST上找到一个节点的引用找到前一个。

public static TreeNode findPredecessor(TreeNode node) {
    if (node == null)
        return null;

    if (node.getLeft() != null)
        return findMaximum(node.getLeft());

    TreeNode parent = node.getParent();

    TreeNode y = parent;
    TreeNode x = node;
    while (y != null && x == y.getLeft())
    {
        x = y;
        y = y.getParent();
    }


    return y;
}

我只是想知道代码的这一部分是做什么的。

TreeNode y = parent;
TreeNode x = node;
while (y != null && x == y.getLeft())
{
    x = y;
    y = y.getParent();
}

return y;

在while循环中间究竟发生了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

在找到前任时,有两种情况。

  1. 如果节点具有非空的左子树,则其前任将是左子树中的最大节点。
  2. 如果它没有左子树,那么如果父项(从感兴趣的节点开始向上遍历),则找到第一个右子项的节点。然后,父节点是前任。
  3. TreeNode y = parent; //parent is node.getParent(); i.,e parent of node.
    TreeNode x = node; //assigns node to x
    while (y != null && x == y.getLeft()) 
    {
        x = y; //the parent becomes the current node 
        y = y.getParent(); //the parent is the parent of the parent
    }
    
    return y;
    

    while条件(y != null && x == y.getLeft())表示要继续

    • parent为非null且

    • 当前节点是其父节点的左子节目。即,继续前往找到其父母右子女的节点。

    • 返回父节点作为结果。

    让我们看一下

    的例子
        40
     30    50
              60
            55
          54
        53
    

    有序遍历给出了

    30 40 50 53 54 55 60
    

    55的前身 - 左子树中最大的节点 - 54

    53的前身 - 当向上遍历时,节点是其父节点的右子节点是60 - 其父节点50是结果。

相关问题