Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, I assume that your <code>level order traversal</code> is basically a BFS.</p> <p>Now, let's have a look at the string. Performing the BFS, we print "1" if the current node's got two sons. Otherwise, it's a leaf and we print 0, terminating the processing of the current branch.</p> <p>Consequently, during the reverse task, we can remember the list of open branches' last nodes and append the incoming nodes there.</p> <p>Let's demonstrate this approach on an example:</p> <pre><code>Level 1: Tree : 1 - id 0 Open branches : 0 0 (left and right son) Remaining string : 11001000 ********* Level 2: Tree : 1 1 1 Open branches : 1 1 2 2 Remaining string : 001000 ********* Level 3: Tree : 1 1 1 0 0 1 0 Open branches : 5 5 Remaining string : 00 Level 4: Tree : 1 1 1 0 0 1 0 0 0 No more input, we're done. </code></pre> <p>Having the tree, the post-order traversal is trivial.</p> <p>And the code (it assumes that the tree is quite dense, otherwise it's not very memory efficient): </p> <pre><code>import java.util.ArrayDeque; import java.util.Queue; public class Main { static final int MAX_CONST = 50; public static void main(String[] args) { String evilString = "111001000"; // Assuming this string is a correct input char[] treeRepr = new char[MAX_CONST]; Queue&lt;Integer&gt; q = new ArrayDeque&lt;Integer&gt;(); q.add(0); for (int i = 0; i &lt; evilString.length(); ++i) { int index = q.remove(); char ch = evilString.charAt(i); if (ch == '1') { q.add(2*(index+1)-1); q.add(2*(index+1)); } treeRepr[index] = ch; // System.out.println(q.size()); } System.out.println(arrToString(treeRepr, 0, new StringBuilder())); } public static StringBuilder arrToString(char[] array, int index, StringBuilder sb) { if (array[index] == '1') { arrToString(array, 2*(index+1)-1, sb); arrToString(array, 2*(index+1), sb); } sb.append(array[index]); return sb; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload