Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose you are given two lists containing the contents of a binary tree, one th

ID: 3644882 • Letter: S

Question

Suppose you are given two lists containing the contents of a binary tree, one that gives the elements as listed by a breadth-first traversal, and a second, parallel list that gives the number of children of each node. From these two lists, rebuild the original tree.

Explanation / Answer

public class StringPartitioner implements Iterator, Iterable { String s; // the string to be partitioned int m; // the number of partitions int prefix; // the index such that s.substring(0, prefix) is the first partition StringPartitioner tailGenerator; // The Iterable interface requires the iterator() method. But // this is trivial. The StringPartitioner class is an Iterator, // so just return this. public Iterator iterator() { return this; } // Precondition: m is positive, s.length() >= m public StringPartitioner(String s, int m) { this.s = s; this.m = m; if (m > 1) { prefix = 1; tailGenerator = new StringPartitioner(s.substring(1,s.length()), m-1); } else { prefix = 0; } } public String next() { if (tailGenerator != null) { // We maintain the invariant that a non-null // tailGenerator always has next. So the following // call is safe. String tail = tailGenerator.next(); String head = s.substring(0,prefix); if (!tailGenerator.hasNext()) { // Fix the tailGenerator. Make sure that a // non-null tailGenerator always has next. if (s.length() - prefix >= m) { prefix++; tailGenerator = new StringPartitioner(s.substring(prefix, s.length()), m - 1); } else { tailGenerator = null; } } return head + "|" + tail; } else if (m == 1) { // In this case, one partition is the whole string. We // first set prefix to -1 as a flag indicating that // this output has been returned and the next call to // hasNext() will return false. prefix = -1; return s; } else { return null; } } public boolean hasNext() { // It's clear that there is a next if the tailGenerator // has a next. The other case, with prefix == 0 only // occurs where m == 1, i.e., the number of partitions is // just one. Moreover the 0 is changed to -1 after the 1 // partition has been returned by next() so that it won't // be returned multiple times. return tailGenerator != null || prefix == 0; } public void remove() { throw new UnsupportedOperationException(); } public static void main(String[] args) { StringPartitioner sp = new StringPartitioner("abcde", 3); for (String s : sp) { System.out.println(s); } } }
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote