我不明白此递归如何打印树

时间:2019-09-14 10:07:21

标签: python recursion binary-search-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)

我已经完成了尽可能多的演练,但最终我遇到了None循环,关于它我不知道它如何继续进行

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

0 个答案:

没有答案