Python Trees: Modifying a tree

439 views Asked by At

This is my python code to make an Ordered Binary Decision Diagram (not very relevant for the context). So I just have a tree of a particular height, and I need to set some of the leaf nodes to one. So I have a variable path which involves an array of "decisions", to go left or right from that particular node. But my code is by mistake modifying multiple roots. I am fairly new to Python and I used to rely on pointers when I used C.

def makeCubes(arr):
        ans = []
        for ar in arr:
            ar2 = [ar[i:i + 2] for i in range(0, len(ar), 2)] 
            #splitting into segments of 2 each
            if not '00' in ar2:
                ans += [ar2]
        return ans

class Node:
    def __init__(self,key):
        self.key = key
        self.left = None
        self.right = None
    def addLeft(self,node):
        self.left = node
    def addRight(self,node):
        self.right = node

def makeTree(size):
    if(size == 1):
        leaf = Node('x0')
        leaf.addLeft(Node('zero'))
        leaf.addRight(Node('zero'))
        return leaf
    else:
        node = Node('x'+str(size-1))
        childNode = makeTree(size-1)
        node.addLeft(childNode)
        node.addRight(childNode)
        return node

def inOrder(root):
    if(root != None):
        return inOrder(root.left) + [root.key] + inOrder(root.right)
    return []

def makeOBDD(array):
    maxLen = max([len(word) for word in array])
    tree = makeTree(maxLen)
    for cube in array:
        tree = makeOne(tree,cube)
    return tree

def makeOne(root,cube):
    print("cube",cube)
    if(cube == []):
        print("updated")
        root.key = 'one'        
    else:
        element = cube[0]
        if(element == '01'):
            root.addLeft(makeOne(root.left,cube[1:]))
        elif(element == '10'):
            root.addRight(makeOne(root.right,cube[1:]))
    return root

# ab + a'b'
'''
Expected output
   x1
  /  \
 x0   x0
/ \   / \ 
1  0  0  1
'''
cubeSet = ['1010','0101']
cubes = makeCubes(cubeSet)
print(cubes)
obdd = makeOBDD(cubes)
print(inOrder(obdd))
0

There are 0 answers