以递归方式打印二进制搜索树

时间:2015-04-19 20:30:29

标签: java

我有使用递归按顺序(升序)打印二叉搜索树内容的代码。我知道辅助方法调用递归方法,以root作为起始节点值。但我不明白递归代码在概念上是如何工作的。谁能解释一下?

//ascend method that prints values in the tree in ascending order
//recursive method below
public void printAscending() {
    printAscending(root);
}
private void printAscending(Node node) {
    if(node != null) {
        printAscending(node.left);   
        System.out.println(node.data);
        printAscending(node.right);  
    }
}

3 个答案:

答案 0 :(得分:2)

// public entry point, reuses the recursive function
public void printAscending() {
    printAscending(root);
}

// print this node and all of its descendants
private void printAscending(Node node) {
    // is there actually a node here
    // or was this called from a node with no children
    if(node != null) {
        // print everything that's earlier than this node
        printAscending(node.left);   

        // print this node's value
        System.out.println(node.data);

        // print everything that's afterthan this node
        printAscending(node.right);  
    }
}

答案 1 :(得分:2)

考虑以下(普通)树:

1

您正在调用一个(根)上的函数,很明显看到结果是1

现在考虑以下(稍大)树:

 2
1

根目前为2,输出(手动手动跟踪)给出1 2(为清晰起见添加了空格)

以下类似的手动追踪为我们提供了1 2 3

 2
1 3

所以我们现在可以看到,对于小型测试用例,似乎工作正常。

让我们尝试为更大的测试用例证明它。

对于任何空节点(即如果我们处于不存在的树/子树),我们就退出。

对于任何非空节点,首先调用printAscending(node.left)行。该行必须在其他任何运行之前完成执行。这使用printAscending()作为参数调用node.left函数,这相当于只查看当前节点的左子树,完成那里的工作然后继续编码。我们可以继续向左走,直到我们到达一个空节点。在这个时间点,它向上移动,从它停止的地方恢复。它运行System.out.println(node.data),它提供单个节点的输出,然后运行printAscending(node.right)。这会导致它进入当前节点的右子树。请注意,在此子树中,它运行完整的代码(即运行左侧,中间和右侧部分)。一旦完成运行正确的子树,它就会退出子树和当前节点。这使得位于其上方的节点(父节点)移动到代码的下一部分。

如果您遵循类似的工作,您将看到根首先处理根的整个左子树,然后打印根,然后处理整个右子树。

答案 2 :(得分:0)

    public void printInOrder() {
        if (left != null) {
            left.printInOrder();
        }
        System.out.println(data);
        if (right != null) {
            right.printInOrder();
        }
    }
相关问题