在二叉搜索树中查找父级

时间:2014-11-20 08:02:57

标签: java recursion binary-search-tree

以下是在二进制搜索树中查找父级的代码。我无法理解它是如何工作的,因为我们永远不会将任何值分配给除null之外的父级。我是一个新的递归。

public Node findParent(Type data) 
{
    return findParent(data, root, null);
}

public Node findParent(Type x, Node node, Node parent) 
{
    if (node == null) {
        return null;
    } else if (!(node.data == x)) {
        parent = findParent(x, node.left, node);
        if (parent == null) {
            parent = findParent(x, node.right, node);
        }
    }
    return parent;
}

2 个答案:

答案 0 :(得分:1)

您在递归调用中为父级分配非空值:

parent = findParent(x, node.left, node);
                                  ----
parent = findParent(x, node.right, node);
                                   ----

parent仅在初始调用中为空(因为树的根没有父级)。

findParent的每次调用都会获得一个值(x),一个节点(node)和该节点的父节点(parent)。如果在Node中找到该值,则返回parent,否则,在左子树中搜索该值,如果仍未找到,则在右侧子树中搜索它。 / p>

答案 1 :(得分:0)

我在这里写了一些评论。如果看起来不清楚,请告诉我。 (递归很难解释)

// The method
public Node findParent(Type x, Node node, Node parent)
{
    // if this node is null, return null, cause this 
    // is not the path you are looking for
    if (node == null) {
        return null;
        // if this is not the node we are looking for,
    } else if (!(node.data == x)) {
        // We look in the left node.
        parent = findParent(x, node.left, node);
        // If its not found parent will be null
        if (parent == null) {
            // So we go look to the right
            parent = findParent(x, node.right, node);
        }
    }
    // Eventually we can return the parent.
    // If this was the node we were looking for,
    // We can return parent without changing it.
    // If it was not, this algorithm searched in its subtrees
    // If its not there than parent is null.
    return parent;
}