public class TrinaryNode{
int val;
TrinaryNode left;
TrinaryNode right;
TrinaryNode middle;
TrinaryNode(int x){
this.val = x;
}
}
TrinaryNode root;
TrinaryTree(){
root = null;
}
TrinaryTree(int x){
root = new TrinaryNode(x);
}
TrinaryNode insert(TrinaryNode root, int x){
TrinaryNode tmp = new TrinaryNode(x);
if(root==null){
root = tmp;
return root;
}
if(root.val > x){
if(root.left==null){
root.left = tmp;
}
else{
insert(root.left, x);
}
}
if(root.val < x){
if(root.right==null){
root.right = tmp;
}
else{
insert(root.right, x);
}
}
if(root.val == x){
if(root.middle==null){
root.middle = tmp;
}
else{
insert(root.middle, x);
}
}
return root;
}
TrinaryNode delete(TrinaryNode root, int x){
if(root.val > x){
root.left = delete(root.left, x);
}
else if(root.val < x){
root.right = delete(root.right, x);
}
else if(root.middle != null){
root.middle = delete(root.middle ,x);
}
else if(root.right !=null){
root.val = Sucessor(root.right).val;
delete(root, Sucessor(root.right).val);
}
else {
root = root.left;
}
return root;
}
TrinaryNode Sucessor(TrinaryNode root){
TrinaryNode tmp = root;
while(tmp.left!=null){
tmp=tmp.left;
}
return tmp;
}
void test_print(TrinaryNode root){
if (root!=null){
System.out.println("Node Value: " + root.val);
}
else return;
test_print(root.left);
test_print(root.middle);
test_print(root.right);
}