Note that there are some explanatory texts on larger screens.

plurals
  1. POFinding first element in a Left-Child Right-Sibling Tree
    primarykey
    data
    text
    <p>In a recent interview, I was asked this question. Given a left-child, right sibling tree, find the first node in the tree that holds a true value. (first defined as on the highest level, answer could be implemented in either C++ or Java</p> <p>My answer is below and I believe it works based on the test cases I have run so far. I was wondering if there is a more elegant solution. I'm using 3 queues right now and that does not seem optimal.</p> <pre><code>private class Node{ Node child; Node sibling; boolean data; } Node findFirstTrue(Node n) { if (n == null) { return null; } if (n.data == true) { return n; } Queue&lt;Node&gt; searchNextSibling = new ArrayDeque&lt;Node&gt;(); Queue&lt;Node&gt; searchNextChildren = new ArrayDeque&lt;Node&gt;(); searchNextSibling.add(n); while(!searchNextSibling.isEmpty() || !searchNextChildren.isEmpty()) { while(!searchNextSibling.isEmpty()) { Node current = (test.Node) searchNextSibling.remove(); if (current.data == true) { return current; } if (current.sibling != null) { searchNextSibling.add(current.sibling); } if (current.child != null) { searchNextChildren.add(current.child); } } Queue&lt;Node&gt; tempQueue = new ArrayDeque&lt;Node&gt;(); while (!searchNextChildren.isEmpty()) { Node current = (test.Node) searchNextChildren.remove(); if (current.data == true) { return current; } if (current.sibling != null) { searchNextSibling.add(current.sibling); } if (current.child != null) { tempQueue.add(current.child); } } searchNextChildren.addAll(tempQueue); } return null; } </code></pre>
    singulars
    1. This table or related slice is empty.
    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.
 

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