简体   繁体   中英

How to cause side effects to an instance variable in python?

I am trying to implement a Binary Search Tree in python to practice recursion skills, but my head variable isn't updating on the first call to add() . It continues to stay at a null value even though it should be updated on the first call as it is the currentNode . What am I doing wrong?

class BinarySearchTree:
    class Node:
        def __init__(self, data):
            self.data = data
            self.Right = None
            self.Left = None

    head = None

    def __init__(self):
        self.head = None

    def add(self, newNode):
        self.__addrecursive(self.head, newNode)

    def __addrecursive(self, currentNode, valueToAdd):
        if currentNode is None:
            currentNode = self.Node(valueToAdd)
            return currentNode
        elif valueToAdd < currentNode.data:
            return self.__addrecursive(self, currentNode.Left, valueToAdd)
        else:
            return self.__addrecursive(self, currentNode.Right, valueToAdd)
import BinarySearchTree as treelib

tree = treelib.BinarySearchTree()
tree.add("Apple")
print(tree.head) #Head should contain "Apple" but is intead None

I have made a few changes to your code.

  1. removed the head = None which is never used
  2. addded self.head = inside the add function becaues previously __addrecursive was returning a node but it wasn't being assigned to anything
  3. in the case where currentNode is None just return the node directly rather than assigning to currentNode
  4. remove the self argument to each of the recursive calls
  5. assign the return value of the recursive call to the left or right side of the currentNode
  6. return the currentNode at the end which bring everything back up to the top level and be returned and assigned to self.head
class BinarySearchTree:
    class Node:
        def __init__(self, data):
            self.data = data
            self.Right = None
            self.Left = None

    def __init__(self):
        self.head = None

    def add(self, newNode):
        self.head = self.__addrecursive(self.head, newNode)

    def __addrecursive(self, currentNode, valueToAdd):
        if currentNode is None:
            return self.Node(valueToAdd)
        elif valueToAdd < currentNode.data:
            currentNode.Left = self.__addrecursive(currentNode.Left, valueToAdd)
        else:
            currentNode.Right = self.__addrecursive(currentNode.Right, valueToAdd)
        return currentNode

I don't really know about binary trees so I could be wrong because I just copied some code from here: https://www.geeksforgeeks.org/binary-search-tree-set-1-search-and-insertion/

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