Java 以递归顺序打印二叉搜索树

Java 以递归顺序打印二叉搜索树,java,Java,我有使用递归按顺序(升序)打印二进制搜索树内容的代码。我知道helper方法调用以root作为起始节点值的递归方法。但我不明白递归代码在概念上是如何工作的。有人能解释一下吗 //ascend method that prints values in the tree in ascending order //recursive method below public void printAscending() { printAscending(root); } private void

我有使用递归按顺序(升序)打印二进制搜索树内容的代码。我知道helper方法调用以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);  
    }
}
考虑以下(琐碎的)树:

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

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

根现在是
2
,输出(手动跟踪)给出
12
。(为清晰起见,增加了空格)

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

 2
1 3
所以我们现在可以看到,对于小型测试用例,它似乎工作得很好

让我们试着用更大的测试用例来证明它

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

对于任何非空节点,首先调用
printsupsing(node.left)
行。这一行必须在其他任何操作运行之前完成执行。这将使用
node.left
作为参数调用
printsupsing()。我们可以一直向左走,直到到达一个空节点。此时,它向上移动,从停止的位置恢复。它运行
System.out.println(node.data)
,给出单个节点的输出,然后运行
printsupsing(node.right)
。这将导致它进入当前节点的右子树。请注意,在此子树中,它运行完整的代码(即运行左、中、右部分)。在右子树中运行完成后,它将退出子树和当前节点。这使其正上方的节点(父节点)移动到代码的下一部分


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

重复:@SebastiaanvandenBroek请避免以后进行无意义的编辑。为单个空间编辑帖子是不值得的。我认为递归函数的问题在于,你要么可以看到它们是如何工作的,要么看不到。工作示例是一个好主意。要了解有关递归的更多信息,请重新阅读此注释。:)最好先解释这个场景,然后再解释为什么你的答案有效。
    public void printInOrder() {
        if (left != null) {
            left.printInOrder();
        }
        System.out.println(data);
        if (right != null) {
            right.printInOrder();
        }
    }
 2
1
 2
1 3
    public void printInOrder() {
        if (left != null) {
            left.printInOrder();
        }
        System.out.println(data);
        if (right != null) {
            right.printInOrder();
        }
    }