0

I've been practicing data structures i'm able to insert a node and display , but i'm not able to understand the recursion used to display the tree

class node:
    def __init__(self, data=None):
        self.data = data
        self.right = None
        self.left = None


class Binary_search_tree:
    def __init__(self):
        self.root = None
        self.i = 0

    def insert(self, value):
        if self.root == None:
            self.root = node(value)
        else:
            self._insert(value, self.root)

    def _insert(self, value, current_node):
        if value > current_node.data:
            if current_node.right == None:
                current_node.right = node(value)
            else:
                self._insert(value, current_node.right)
        elif current_node.data > value:
            if current_node.left == None:
                current_node.left = node(value)
            else:
                self._insert(value, current_node.left)

    def display(self):
        if self.root != None:
            self._display(self.root)

    def _display(self, current_node):
        if current_node != None:
            self._display(current_node.left)
            print(current_node.data)
            self._display(current_node.right)

I've done as many walkthroughs as i can but i end up with the None loop, about which i have no idea how it further proceeds

    def _display(self, current_node):
        if current_node != None:
           self._display(current_node.left)
           print(current_node.data)
           self._display(current_node.right)
Chandru
  • 467
  • 1
  • 8
  • 17
  • the `_display()` function is using [in-order tree traversal](https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/). –  Sep 14 '19 at 10:18
  • Here's a 3-minute youtube video that explains inorder tree traversal: https://www.youtube.com/watch?v=5dySuyZf9Qg – DarrylG Sep 14 '19 at 10:32
  • i know how inorder tree traversal works ,its just i dont understand how the recursion works here – Chandru Sep 14 '19 at 10:52
  • @Chandru - [this question](https://stackoverflow.com/questions/23744913/how-does-this-inorder-traversal-algorithm-work) has a pretty good explanation. You can think of each invocation of the `_display()` function as potentially creating deep tunnels of execution, in that a call to `_display()` may spawn a new execution of `_display()`, which in turn might spawn a new `_display()` execution ... and so on. When, finally, a call to `_display()` does not respawn and returns i.e. `current_node != None` is false, execution resumes at the statement *just after* the most recent call to `_display()`. –  Sep 14 '19 at 14:31
  • Thanks @BithikaMookherjee ,the tunnel analogy was intuitive – Chandru Sep 14 '19 at 16:08

0 Answers0