algorithm - Reconstructing a tree using inorder and preorder traversals in Python -
I need to create a function that creates a tree from the preorder and the indoor traversel, but I'm not sure where Put the MacNode and recursive calls to make the panel properly.
There is a list of entrees considering the iners and the preederers, both of which are the following algorithms for rebuilding trees using trailers?
def build (preorder, inorder): root = preorder [0] subtree = inorder [: root-1] true subtree = inorder [root + 1:] If so - how can he take it and use that algorithm in a recursive form to create arahep? I have a class designed to build nodes and then I can use just H.P.AD (node) to make a pile.
Ask me to create a node for the node, named "MacDoode" and its construction is as follows (for syntax purposes):
class makeonode (): def __init __ (self, character, left = none, right = none): The root node I have to edit the function like this:
Def build (preorder, inorder, heap): root = preorder [0] node = mcod (root) # build root node here heap .add (node) #adding the heap subtree = inorder [: root-1] right subtree = inorder [root + 1:] But how should I use recursion to build the rest of the tree?
I can include the left and right preorder to sort the objectives by doing this:
def build (preorder, inorder, heap): root = preorder [0] Node = MakeNode (root) heap.add (node) left subtree = inorder [: root-1] # left sequence # preorder [1: 1 + left subtree] right subtree = inorder [root + 1:] # command right Subtree = Preorder's [Route + 1:] I do not know exactly how to include a recursive call to make a tree or what to fix for the left or right parameters, by doing this .
If someone has any suggestions, then I appreciate them, and I'm sorry, if I have been told to be ambiguous.
What do you need to do to add the root of the pre-ordered list to the tree, and remove it Divide the order from the preorder list to the order, as you are doing, then both the left and right branches are going through repetition. Keep adding the first element of the pre-order to the left of the previous node, unless the left_subtree is empty, you have to add it to the right
something like this (since asking for pseudo code The tree of the class (): def __init __ (self, inside, pre-order): self .root = preorder [0] lt = inorder [: Index (self.root) - 1] RT = Indoor [index (self.root) + 1:] self.build (self.root, lt, rt, preorder [1:] def (self, final_ode, byte_subtree, right_subtree, Pred Od): If lane (left_subtree)> gt: last_node.left = preorder [0] last_node = last_node.left lt = left_subtree [: index (pre-order [0]) 1] rt = left_subtree [index (pre-orders [0] ) + 1:] self.build (last_node, lt, rt, preorder1) alif lane (right_subtree)> gt: last_node.right = preorder [0] last_node = Last_node.right lt = right_subtree [: index (preorder [0] ) - 1] RT = Right_subtree [Index (Preder [0]) + 1:] Build (Last_Net, Lieutenant, RT, Preder 1:]
Comments
Post a Comment