I am writing a function to determine the size of a binary search tree. I tried it in a recursive way:
def size(self) -> int: #self representing the whole bst
"""Return number of nodes contained in the tree."""
if self._root is None:
return 0
else:
return self._size(self, 0, self._root)
def _size(self, current_size, current_node):
if current_node != None:
current_size += 1
if current_node.left != None:
current_size += self._size(current_size, current_node.left)
if current_node.right != None:
current_size += self._size(current_size, current_node.right)
return current_size
However, this throws a TypeError for the line:
return self._size(self, 0, self._root)
TypeError: 'int' object is not callable
I am new to the recursive functions and somehow cannot really find out how the helper function and the original function should work together and if my approach is going into the right direction. Therefore, any help is much appreciated.
Here are the codes for the classes:
from typing import Any
class TreeNode:
def __init__(self, key: int, value: Any, right: 'TreeNode' = None,
left: 'TreeNode' = None, parent: 'TreeNode' = None):
"""Initialize TreeNode.
Args:
key (int): Key used for sorting the node into a BST.
value (Any): Whatever data the node shall carry.
right (TreeNode, optional): Node to the right, with a larger key. Defaults to None.
left (TreeNode, optional): Node to the left, with a lesser key. Defaults to None.
parent (TreeNode, optional): Parent node. Defaults to None.
"""
self.key = key
self.value = value
self.right = right
self.left = left
self.parent = parent
from tree_node import TreeNode
class BinarySearchTree:
"""Binary-Search-Tree implemented for didactic reasons."""
def __init__(self, root: TreeNode = None):
"""Initialize BinarySearchTree.
Args:
root (TreeNode, optional): Root of the BST. Defaults to None.
"""
self._root = root
self._size = 0 if root is None else 1