1

Result is initialized as None. Result is updated with insertNode. Since Result is None, insertNode should have updated Result with the argument Node.

But I'm getting None even after insertNode method call.

Trying to Merge two Binary-Search-Tree

class Node:
    def __init__(self, value):
        self.left = None
        self.data = value
        self.right = None
def insert(root, node):
    if root is None:
        root = node
    else:
        #usual code to insert other nodes..... 

methods I'm implementing

def merge(root1, root2):
    if (root1 is None):
        return root2

    if (root2 is None):
        return root1

    result = None

    mergeUtil(result, root1, root2)

    return result

def mergeUtil(result, root1, root2):

    mergeUtil(result, root1.left, root2)
    mergeUtil(result, root1, root2.left)

    if(root1.data < root2.data):
        insert(result, Node(root1.data))
        print(type(result))

    else:
        insert(result, Node(root2.data))
        print(result.data)



    mergeUtil(result, root1.right, root2)
    mergeUtil(result, root1, root2.right)

I'm getting class 'NoneType' for print(type(result)) under mergeUtil(...)

WHY? result should be pointed to Node(root1.data) or Node(root2.data) right?

PS: I Know the above code will not actually achieve anything in terms of merging BSTs. Work in progress.

  • When you pass `result` to `mergeUtil()`, the function receives the value `None`. It does NOT gain any ability to reassign the variable that this value came from. Inside a function, the parameters are just local variables. – jasonharper Jul 29 '19 at 23:58
  • How do I pass result=None as reference and not as value to insert(...) ? – RaviKishore Jul 30 '19 at 00:16
  • Either pass a mutable value of some sort (and mutate it rather than reassigning it), or return a new value and require that callers of the function reassign the new value themselves. – jasonharper Jul 30 '19 at 00:34

0 Answers0