简体   繁体   中英

How to understand a recursive inorder traversal of a BST in Java?

I am trying to understand how the well-established methods of implementing an inorder traversal of a binary search tree are functioning in Java.

I am given the following code:

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

with isEmpty() returning whether the current Node is null , getValue() returning the value of the current node, and getLeft() as well as getRight() respectively returning the left and right successor node.

My problem here is, I do not understand how one is able to process the traversal with this code. I have visualized my chain of thoughts on a sheet of paper for you guys to see, with the circles being the nodes, the black squares being null nodes, and the encircled node being the current (this) object. As I am following the pseudocode, I would land in a null node at the end and hit the recursive dead-end case. I also do not at all understand how the code is able to go back in the tree hierarchy once we've already set subtree nodes as the current this object.

My visualization

Am I imagining this wrong, and if so, could someone help me understand the right way of doing this? The code works, but I really need to understand how that comes through. Any help would be super super appreciated

As I am following the pseudocode, I would land in a null node at the end and hit the recursive dead-end case

When you reach the "dead-end" case, this means the current branch of the recursion tree ends. It doesn't mean the entire recursion ends.

After all, when method X calls method Y, and method Y ends, the control returns to method X. This remains true when methods X and Y have the same name. The recursion only ends after the original inorder() call (which was executed on the root of the tree) returns.

You can number each call to the inorder() method in order to tell them apart:

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)

and so on...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM