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 :)

There is a discrepancy in these 2 statements. Is preorder a list, so preorder[0] can be None, or is preorder a string, i.e the second statement below?

if (preorder[0] or inorder[0]) is None: 
    if preorder is not None:

thx I fixed it :)

hey eva, I looked at your code and it looks right to me, I'm interested in knowing what change have you made to your code to fix the error

thanks

Hey guys I'm having the same problem. What is wrong with eva's code?
Eva, can you post the final solution?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.