In: Computer Science
How could I implement the contain and min method for a tree in this code. import java.util.List; import edu.princeton.cs.algs4.*; class ProgrammingAssignment1 { //////////////////// EXERCICE 1: TWO THREE TREES static public <Key extends Comparable<Key>> int size (NakedTree<Key> tree) { if (tree == null) return 0; int val = tree.getNKeys (); for (int i = 0; i <= tree.getNKeys (); ++i) val += size (tree.getChild (i)); return val; } //////// EXERCICE 1.1: contains AND min static public <Key extends Comparable<Key>> boolean contains (NakedTree<Key> tree, Key key) { }
public static <Key extends Comparable<Key>> Key min(NakedTree<Key> tree) { if(tree == null) { return null; } Key min = null; for(int i=0; i<tree.getNKeys(); i++) { if(min == null || min.compareTo(tree.getKey(i)) > 0) { min = tree.getKey(i); } } for (int i = 0; i <= tree.getNKeys(); ++i) { Key m = min(tree.getChild(i)); if(m != null && min.compareTo(m) > 0) { min = m; } } return min; } static public <Key extends Comparable<Key>> boolean contains(NakedTree<Key> tree, Key key) { if(tree == null) { return false; } for(int i=0; i<tree.getNKeys(); i++) { if(key.compareTo(tree.getKey(i)) == 0) { return true; } } for (int i = 0; i <= tree.getNKeys(); ++i) { if(contains(tree.getChild(i), key)) { return true; } } return false; }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.