/media/sda-magnetic/david/Dok-15-2023-11-27/fernuni-hagen/cs-i-ii/old-cs-2-03/java-new/2020-11-23/BinaryTreeProgParam.java


public class BinaryTreeProgParam {
    public static void main (String [] args) {
        try {
            int i;
            BinTree <Person> root = new BinTree <Person> (new Person(args[0], args[1]));
            
            for (i = 2;  i < args.length;  i+=2)
                root.insertBinTree (new Person(args[i], args[i+1]));
            root.traverseBinTree();
            
            BinTree <String> root2 = new BinTree <String> (args[0]);
            for (i = 1;  i < args.length;  i++)
                root2.insertBinTree (args[i]);
            root2.traverseBinTree();
            
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println ("You have to give one argument at least");
        }
    }
    
    public static class Person implements Comparable {
        String firstname;
        String lastname;
        
        Person (String firstname, String lastname) {
            this.firstname = firstname;
            this.lastname = lastname;
        }
        
        @Override
        public int compareTo (Object o) {
            Person p = (Person) o;
            
            return this.toString().compareTo (p.toString());
        }
        
        @Override
        public String toString () {
            return lastname + ", " + firstname;
        }
    }
    
    public static class BinTree <P extends Comparable> {
        BinTree r;
        BinTree l;
        P v;
        
        BinTree (P v) {
            this.v = v;
            this.l = null;
            this.r = null;
        }
        
        void insertBinTree (P v) {
            if (this.v.compareTo (v) < 0) {
                if (this.l == null)
                    this.l = new BinTree (v);
                else    
                    this.l.insertBinTree (v);
            }
            else {
                if (this.r == null)
                    this.r = new BinTree (v);
                else
                    this.r.insertBinTree (v);
            }
        }
        
        void traverseBinTree () {
            if (this.l != null)
                this.l.traverseBinTree ();
            System.out.println (this.v.toString());
            if (this.r != null)
                this.r.traverseBinTree ();
        }
    }
}