如何理解Java中BST的递归顺序遍历?
我试图理解在Java中实现二叉搜索树的有序遍历的成熟方法是如何工作的 我得到了以下代码:如何理解Java中BST的递归顺序遍历?,java,binary-search-tree,Java,Binary Search Tree,我试图理解在Java中实现二叉搜索树的有序遍历的成熟方法是如何工作的 我得到了以下代码: public void inorder() { if (!this.isEmpty()) { this.getLeft().inorder(); System.out.print(this.getValue()); this.getRight().inorder(); } } 使用isEmpty()返回当前
public void inorder() {
if (!this.isEmpty()) {
this.getLeft().inorder();
System.out.print(this.getValue());
this.getRight().inorder();
}
}
使用isEmpty()
返回当前节点是否为null
,getValue()
返回当前节点的值,getLeft()
以及getRight()
分别返回左后继节点和右后继节点
我这里的问题是,我不理解如何用这段代码处理遍历。我已经在一张纸上可视化了我的思想链,让你们看到,圆圈是节点,黑色正方形是空节点,被包围的节点是当前(这个)对象。当我遵循伪代码时,我会在结尾处到达一个空节点,并碰到递归死端情况。我也完全不理解,一旦我们已经将子树节点设置为当前对象,代码如何能够回到树层次结构中
我是否认为这是错误的,如果是,有人能帮助我理解正确的做法吗?代码是有效的,但我真的需要理解它是如何实现的。任何帮助都将不胜感激
当我遵循伪代码时,我会在结尾处到达一个空节点,并遇到递归死端情况
当您到达“死胡同”情况时,这意味着递归树的当前分支结束。这并不意味着整个递归结束
毕竟,当方法X调用方法Y,并且方法Y结束时,控件返回到方法X。当方法X和Y具有相同的名称时,情况仍然如此。只有在原始的inoorder()
调用(在树的根上执行)返回后,递归才会结束
您可以对每个调用inoorder()
方法进行编号,以便区分它们:
1. root.inorder() calls
2. root.getLeft().inorder() calls
3. root.getLeft().getLeft().inorder() calls
4. root.getLeft().getLeft().getLeft().inorder()
this node is empty, so inorder() #4 method returns control to the previous one (#3)
now #3 call prints the current node via System.out.print(this.getValue())
which prints the left most node of the tree
then #3 calls
5. root.getLeft().getLeft().getRight().inorder()
this node is also empty, so the current inorder() method returns control to #3
now #3 also ends, and returns control to the previous method (#2)
等等……在“null”节点上进行调用后,您认为会发生什么?我的感觉是,该方法完全结束了,因为我们只在当前节点不为null时才进入if情况……谢谢Eran,这是我错过的关键点。。。。干杯