0

This might be some python language thing but I am not able to wrap around my head on this.

When putting values in children of one TreeNode object makes children of other objects point to the children list of original object.

def createTree(parent, value):
    nmap = {}

    for i, v in enumerate(value):
        nmap[i] = TreeNode(v)

    for i, v in enumerate(parent):
        if v is not -1:
            print("adding child for node: " + str(v))
            nmap[v].children.append(nmap[i])
        else:
            print("Not adding")

class TreeNode:
    val = None
    children = []

    def __init__(self, v):
        self.val = v

createTree([-1,0,0,1,2,2,2],[0,1,2,3,4,5,6])

enter image description here

Sensiblewings47
  • 558
  • 1
  • 5
  • 16
  • 2
    `children` is a _class attribute_, it's _supposed_ to be shared. _"putting values in children of one TreeNode object makes children of other objects point to the children list of original object"_ - no, there was only ever one list to start with. See e.g. https://stackoverflow.com/q/1680528/3001761. – jonrsharpe Aug 07 '23 at 21:01
  • @jonrsharpe Ah, thank you for pointing that out. I come from Java world and this is not what I expected. – Sensiblewings47 Aug 07 '23 at 21:04

0 Answers0