[英]How to understand a recursive inorder traversal of a BST in Java?
我试图了解在 Java 中实现二叉搜索树中序遍历的成熟方法是如何运作的。
我得到以下代码:
public void inorder() {
if (!this.isEmpty()) {
this.getLeft().inorder();
System.out.print(this.getValue());
this.getRight().inorder();
}
}
其中isEmpty()
返回当前 Node 是否为null
, getValue()
返回当前节点的值, getLeft()
和getRight()
分别返回左右后继节点。
我的问题是,我不明白如何使用此代码处理遍历。 我已经在一张纸上可视化了我的想法链供你们查看,圆圈是节点,黑色方块是 null 节点,圆圈中的节点是当前(这个)object。 当我遵循伪代码时,我会在最后登陆 null 节点并遇到递归死胡同。 一旦我们已经将子树节点设置为当前的 object,我也完全不明白代码如何能够将 go 返回到树层次结构中。
我是不是想错了,如果是这样,有人可以帮助我理解正确的做法吗? 该代码有效,但我真的需要了解它是如何实现的。 任何帮助都将非常感谢
当我遵循伪代码时,我会在最后登陆 null 节点并遇到递归死胡同
当你到达“死胡同”的情况时,这意味着递归树的当前分支结束。 这并不意味着整个递归结束。
毕竟,当方法 X 调用方法 Y 并且方法 Y 结束时,控件返回到方法 X。当方法 X 和 Y 具有相同名称时,仍然如此。 递归仅在原始inorder()
调用(在树的根上执行)返回后才结束。
您可以对inorder()
方法的每个调用进行编号,以便将它们区分开来:
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)
等等...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.