【问题标题】:How to understand a recursive inorder traversal of a BST in Java?如何理解 Java 中 BST 的递归中序遍历?
【发布时间】:2021-03-25 02:13:20
【问题描述】:

我试图了解在 Java 中实现二叉搜索树中序遍历的成熟方法是如何运作的。

我得到以下代码:

public void inorder() {
       if (!this.isEmpty()) {
           this.getLeft().inorder();
           System.out.print(this.getValue());
           this.getRight().inorder();
       }
   }

isEmpty()返回当前Node是否为nullgetValue()返回当前节点的值,getLeft()getRight()分别返回左右后继节点。

我的问题是,我不明白如何使用此代码处理遍历。我已经在一张纸上可视化了我的想法链供你们查看,圆圈是节点,黑色方块是空节点,而被包围的节点是当前(this)对象。当我遵循伪代码时,我会在最后到达一个空节点并遇到递归死胡同。我也完全不明白一旦我们已经将子树节点设置为当前的 this 对象,代码如何能够回到树层次结构中。

My visualization

我是不是想错了,如果是这样,有人可以帮助我理解正确的做法吗?该代码有效,但我真的需要了解它是如何实现的。任何帮助都将非常感谢

【问题讨论】:

  • 您认为在“null”节点上进行调用后会发生什么?
  • 我的看法是该方法完全结束了,因为我们只有在当前节点不为空时才进入 if-case...

标签: java binary-search-tree


【解决方案1】:

当我遵循伪代码时,我会在最后到达一个空节点并遇到递归死胡同

当您到达“死胡同”的情况时,这意味着递归树的当前分支结束。这并不意味着整个递归结束。

毕竟,当方法 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)

等等……

【讨论】:

  • 感谢 Eran,这是我错过的关键点……干杯!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
相关资源
最近更新 更多