Do a pre-order of a tree from a master order: In python as much needed to be changed is fine

54 Views Asked by At

I have written this function,self is a tree, and the master order is a list of nodes in which the pre-order traversal needs to be done. See below for an example.

Tree master order As seen in the image The pre-order traversal defined by the master order [6, 4, 3, 1, 2, 5]."

  1. start at the root node 1
  2. scan the children of node 1 in the master order: [4,3,2].
  3. visit node 4(no children, so move on)
  4. visit node 3(no children, so move on)
  5. visit node 2
  6. scan the children of node 2 in the master order: [6,5].
  7. visit node 6(no children, so move on)
  8. visit node 5(no children, so move on)
  9. finish traversal

Note in the code: there is a few functions. One is get_children(self) -> Which returns the immediate children of the node.

#Note just want the pre order working.

def get_children(self) -> List["Node"]:
    """
    Returns the children of the current node.
    :return: The children of the current node.

"""

def get_parent(self) -> "Node":
    """
    Returns the parent of the current node.
    :return: The parent of the current node.
    """



 def pre_order(self, master_order: List[Node]) -> List[Node]:
    """
    Return the pre-order traversal of the tree given a master order.
    This should run in O(N) time for advanced students and O(N^2) time for standard students.
    :param master_order: The master order to use for the pre-order traversal.
    :return: The pre-order traversal of the tree given the master order.
    """
    result = []
    master_idx = 0
    
    def traverse(node: Node, master_idx: int):
        if not node:
            return
        else:
            while master_idx < len(master_order) and node.id != master_order[master_idx]:
                master_idx += 1
                result.append(node)
                for child in node.children:
                    traverse(child, master_idx + 1)
            
    traverse(self.root, 0)
    return result
0

There are 0 best solutions below