Hi,there,
I need to definea function make_tree(preorder, inorder). This function returns the Node which is the root of a binary tree with the pre-order and in-order traversals given as lists of values in the parameters.
If either preorder or inorder is empty, the other must also be empty, and the function's return value is None.
Assume that the parameters represent correct pre-order and in-order traversals of the same binary tree.
My codes are as follows:
class Node(object):
''''A binary tree node.
'''
def __init__(self, key):
"""A Node with the given key."""
self.key = key
self.left = None
self.right = None
_ _ _ _ _ _ _ _ _ _ _
import Node
def make_tree(preorder, inorder):
if (preorder[0] or inorder[0]) is None:
return
if (len(preorder) == 1) and (preorder == inorder):
return preorder[0]
if preorder is not None:
Node.key = preorder[0]
i1 = inorder.index(preorder[0])
i2 = preorder.index(inorder[i1 + 1])
if (i2 == 1) or (i1 == 0):
return None
Node.left = make_tree(preorder[1:i2], inorder[:i1])
Node.right = make_tree(preorder[i2:], inorder[i1 + 1:])
return Node
How can I fix my codes?
Thank you for your time :)