1

I am working on implementing a Java program on inserting and deleting a node in a ternary tree.

I am able to implement insertion without any issues, but I'm facing a few hiccups in implementing the deletion operation.

So, my question is:

How to delete a node from ternary tree if it has one or more child nodes?

It will be great if you can share any logic or pseudo-code to implement the "delete" functionality.

nbro
  • 15,395
  • 32
  • 113
  • 196
Shan
  • 521
  • 2
  • 8
  • 28
  • Have you looked at how B-trees do it? Also, you typically don't want to delete nodes, you want to delete *values*, and those don't have children – Niklas B. Mar 11 '14 at 21:58
  • 2
    Try doing it on a piece of paper first. Start with the simplest case you can think of and try to specify what you want the tree to look like after deletion – “ternary tree” by itself says nothing about which node goes where or which shape the tree has, unless you use the term differently than what I learned ages ago. – Christopher Creutzig Mar 11 '14 at 22:01
  • 1
    Can you specify **few hiccups**? – Cahit Gungor Mar 11 '14 at 22:04
  • The hiccup I am facing is how to delete a node if it has more than one child node. Let me try what @niklas_b told, try moving the data and not deleting the node. – Shan Mar 11 '14 at 22:57
  • For a start, read through the code for deletio in a binary search tree. Understand why it is done that way, and design similar code for yor ternary tree. – vonbrand Mar 12 '14 at 02:13

1 Answers1

1

I found a solution.


Suppose n is the node we want to delete, l is its left child, r is its right child and m is its middle child.

  • If n is a root node, then make n null.

  • If n is not a root node, then check if m is not null. If so, simply invoke recursively the current procedure on m, since m matches n in value: we will delete the last matching node!

  • If m is null, then we have the following possible cases:

    • If both l and r are null, then make l, r and m values in the parent node n to be null.

    • If only one node, say x, (either l or r) is not null, then replace x non-null value with n's value, and delete x.

    • If both l and r are not null, then find the node z with maximum value in the left sub-tree of n, and replace z's value to with n's node, and delete z.

nbro
  • 15,395
  • 32
  • 113
  • 196
Shan
  • 521
  • 2
  • 8
  • 28