Home > Mobile >  BST-analogous structure element insertion recursively
BST-analogous structure element insertion recursively

Time:11-02

I wonder why the author wouldn't simply write the following code instead of the original one. I tested a lot not to miss a case. So, it works as expected. Is it about time-complexity? What point or nuance did I miss?

Think of the elements as [key,value,left-node,right-node]

// my simplification
def insert_binary_tree(x, T):
  if T == []:
      T.extend([x[0], x[1], [], []])
  else:
      if x[0] < T[0]:
          insert_binary_tree(x, T[2])
      else:
          insert_binary_tree(x, T[3])

Original code

def insert_binary_tree(x, T):
    if T == []:
        T.extend([x[0], x[1], [], []])
    else:
        if x[0] < T[0]:
            if T[2] == []:
                T[2] = [x[0], x[1], [], []]
            else:
                insert_binary_tree(x, T[2])
        else:
            if T[3] == []:
                T[3] = [x[0], x[1], [], []]
            else:
                insert_binary_tree(x, T[3])

Example run,

t = ['Emma', '2002/08/23',
['Anna', '1999/12/03', [], []],
['Paul', '2000/01/13',
['Lara', '1987/08/23',
['John', '2006/05/08', [], []],
['Luke', '1976/07/31', [], []]],
['Sara', '1995/03/14', [], []]]]

def insert_binary_tree(x, T):
  if T == []:
      T.extend([x[0], x[1], [], []])
  else:
      if x[0] < T[0]:
          insert_binary_tree(x, T[2])
      else:
          insert_binary_tree(x, T[3])


print(t)
insert_binary_tree(['Abba', '1111/11/11', [], []], t)
print(t)

CodePudding user response:

The only reason could be greater independence between objects. Compare the two codes by slightly changing the input:

empty = []

t = ['Emma', '2002/08/23',
['Anna', '1999/12/03', empty, empty],
['Paul', '2000/01/13',
['Lara', '1987/08/23',
['John', '2006/05/08', empty, empty],
['Luke', '1976/07/31', empty, empty]],
['Sara', '1995/03/14', empty, empty]]]

Now, the original code will still work, but yours won't. You could still simplify it though while maintaining independent references to empty lists:

def insert_binary_tree(x, T):
    if T == []:
        T.extend([x[0], x[1], [], []])
    else:
        child = 2   (x[0] >= T[0])
        if T[child]:
            insert_binary_tree(x, T[child])
        else:
            T[child] = x[:2]   [[], []]  
            # again trying to avoid mutable list references
  • Related