data_pi
data_pi

Reputation: 821

Python - Recursively find parent tree

I have a a binary tree, with only self._root and self._nodes. Is there anyway I could figure out how to find a parent tree of the current tree through the constructor?

class BinaryTree:
    """
    - If _root is None, then _nodes is empty and _parent_tree is None
    - nodes is allowed to contain empty nodes
    - if _parent_tree is not empty, then self is in _parent_tree._nodes
    """
    def __init__(self, root, nodes):
        """Initialize a new BinaryTree.
        @type self: BinaryTree
        @type root: object
        @type nodes: list[BinaryTree]
        @rtype: None
        """
        self._root = root
        self._nodes = nodes
        self._parent_tree = None


        """Implement _parent_tree"""

        if self._root is not None:
            """implement"""
        else:
            pass

To be honest, I have no idea of how to even start this. How would I know any other BinaryTree objects without constructing this one first. What would I be recursively looking through? I can't possibly look through this BinaryTree

Upvotes: 0

Views: 905

Answers (1)

Shasha99
Shasha99

Reputation: 1916

Following should do good for you :

class BinaryTree:
  def __init__(self, root, nodes):
    self._root = root
    self._nodes = nodes
    self._parent_tree = None

    if self._root is not None:
        for node in self._nodes:
            if node is not None:
                node._parent_tree = self
    else:
        pass

Upvotes: 1

Related Questions