Skip to content
Advertisement

Method to delete certain level of binary tree

I have class SimpleTree just basic binary tree:

JavaScript

And the problem is to write method:

JavaScript

Where level is the level of the elements in some tree (root level == 0). For example level == 1:

JavaScript

Only LEFT leaf of DELETED elements is saved, if we dont have such -> save the right.

Advertisement

Answer

Your tree seems to be a recursive data structure.

Suppose you want to delete Level N, then traverse down recursively to N- 1 Step 1 Check at Level N-1 for four cases:

  1. it has a left and a right child (node 2)
  2. it has only a left child (node 6)
  3. it has only a right child (node 10)
  4. no children (node 7)

When you try to delete Level N enter image description here You have to fixup the remaining nodes enter image description here That is why you start at Level N-1, because you need the parent of each node at level N for the fix-up phase.

The four cases above can easily be reduced to:

  • If the left child of the left child exists, set the left child to the left child of the left child. (4.left = 4.left.left)
  • else if the right child of the left child exists, set the left child to the right child of the left child. (4.left = 4.left.right)
  • else NO-OP

For the right child e.g. node 4 it’s exactly the same.

Actually, the fix-up is all you need. Afterwards, let the GC clean up for you and you are done.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement