0

Aren't the Tree insert functions on interactivepython incorrect?

Insert Left:

def insertLeft(root,newBranch):
    t = root.pop(1)
    if len(t) > 1:
        root.insert(1,[newBranch,t,[]])
    else:
        root.insert(1,[newBranch, [], []])
    return root

I found the logic to be incorrect, insertion is leading to a broken tree.

I tried the below (you can run the code on the same page) and see a validation.

r = BinaryTree(3)
insertLeft(r,4)
insertLeft(r,5)
insertLeft(r, [10, [11, [],[]], []])
insertRight(r,6)
insertRight(r,7)
print(r)

Output:

[3, 
    [
        [10, [11, [], []], []], 
            [5, [4, [], []], []], 
            []
    ], 
    [
        7, 
            [], 
            [6, [], []]
    ]
]
sam
  • 777
  • 2
  • 6
  • 19

1 Answers1

0

The result is as intended by those functions. The following:

insertLeft(r, [10, [11, [],[]], []])

...injects a value as the left child of the root. The value that will be given to that new node is what you provided as second argument. This function always creates one new node (triplet) and you have given it the value of a tree structure.

This looks strange in the output, and it looks as if the structure was corrupted, but that is not the case. The value [10, [11, [],[]], []] is just that -- a value -- and it does not take part in structuring the main tree.

Maybe you want to merge two trees. But in that case you should decide what should happen with the subtree at the root's left node. For instance, you could do something like this:

insertLeft(r, 11)
insertLeft(r, 10)

... and then the previous subtree ([5, [4, [], []], []]) will become a child of the node with value 11.

In short, in order to merges subtrees you cannot just pass one subtree as argument to insertLeft. The method is only intended to inject single nodes with one specific value.

trincot
  • 317,000
  • 35
  • 244
  • 286