[Python] Recursive insert method on Binary Tree reaches the correct node but it doesn't save...

Discussão em 'Python' iniciado por Stack, Abril 20, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to make a recursive insert method on a binary tree and while the recursive part of the function seems to do the job correctly (I tracked the code step by step with debug option) when time comes for data to be saved it just doesn't happen. Is it a reference mistake?

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

    class BTree():
    def __init__(self, root=None):
    self.root = root

    def insert(self, data):

    def in_insert(node, data):
    if node is None:
    node = TreeNode(data)
    elif node.data == data:
    print(f'{node.data} already in here.')
    elif node.data > data:
    node = node.left
    in_insert(node, data)`
    else:
    node = node.right
    in_insert(node, data)

    if self.root is None:
    self.root = TreeNode(data)
    else:
    in_insert(self.root, data)

    Continue reading...

Compartilhe esta Página