This may sound silly but trust me , I have searched for various articles online and could not find a proper explanation or no explanation at all , Does it really need two classes one for Node and one for tree to implement binary tree? for Instance , let’s take a simple python code :
class Node(): def __init__(self,data): self.data = data self.left = None self.right = None class BinaryTree(): def __init__(self): self.head = None
this is bascially which I have seen in many online articles , and recently I started working on AlgoExpert course where there was a question about a function which takes Binary tree as Input and an target value as another input and gets the closest value to the target value in tree and return it.
the piece of code given as :
#This is the class of the input root. Do not edit it. class BinaryTree: def __init__(self, data): self.data = data self.left = None self.right = None
Now I am totally confused looking at this snippet , how can I work with just one class ? I am trying to get the concept here , this could sound silly to some people but I would rather ask this question than regret not asking at all. Any input is appreciated .
Advertisement
Answer
Yes, you can use only one class to implement a tree, e.g., Node
class in the first snippet you present is sufficient.
That being said, if you have only one class, you would have to always keep an object referring to the root node, so you can access the tree.
The class BinaryTree
(in the first snippet) could help to do that, but it is not necessary.
Example code using BinaryTree
from the second snippet and declaring a tree:
class BinaryTree: def __init__(self, data): self.data = data self.left = None self.right = None def main(): root = BinaryTree(1) root.left = BinaryTree(2) root.right = BinaryTree(3) if __name__ == "__main__": main()