【问题标题】:printing binary search tree inorder recursively递归打印二叉搜索树
【发布时间】:2018-09-23 22:50:11
【问题描述】:

我有使用递归按顺序(升序)打印二叉搜索树内容的代码。我知道辅助方法调用递归方法以 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);  
    }
}

【问题讨论】:

标签: java


【解决方案1】:

考虑以下(平凡的)树:

1

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

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

 2
1

根现在是2,输出(手动跟踪)给出1 2(为清楚起见添加了空格)

以下类似的手动跟踪给我们1 2 3

 2
1 3

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

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

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

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

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

【讨论】:

  • 我认为关于递归函数的事情是你要么可以看到它们是如何工作的,要么你不能。工作示例是个好主意。要了解有关递归的更多信息,请重新阅读此评论。 :)
【解决方案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);  
    }
}

【讨论】:

    【解决方案3】:
        public void printInOrder() {
            if (left != null) {
                left.printInOrder();
            }
            System.out.println(data);
            if (right != null) {
                right.printInOrder();
            }
        }
    

    【讨论】:

    • 最好先解释一下场景,然后再解释为什么你的答案有效。
    猜你喜欢
    • 1970-01-01
    • 2014-01-02
    • 1970-01-01
    • 2021-07-03
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    相关资源
    最近更新 更多