Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I assume this is homework, so I will give some pointers instead of some code.</p> <ul> <li>your trace method does a recursive descent, therefore the stack is not needed - you can build the path structure while returning from a found node</li> <li>if your method uses a boolean or List return value , you can print the path while returning, or build up a list with the Nodes to print after the search method returns</li> </ul> <p><strong>Edit</strong>: If the path node to root is wanted, a simple boolean return suffices:</p> <pre><code>private boolean trace(Node parent, Node node) { boolean found = (node.data == parent.data) if (!found &amp;&amp; parent.left != null) { found = trace(parent.left, node); } if (!found &amp;&amp; parent.right != null){ found = trace(parent.right, node); } if (found) { System.out.println(parent.data); } return found; } </code></pre> <p>If you need the path from root to node, you can pass a List to receive the nodes in order:</p> <pre><code>private boolean trace(Node parent, Node node, List path) { boolean found = (node.data == parent.data) if (!found &amp;&amp; parent.left != null) { found = trace(parent.left, node); } if (!found &amp;&amp; parent.right != null){ found = trace(parent.right, node); } if (found) { path.add(0, parent); } return found; } </code></pre> <p>alternatively you can build the path on your way back and return as a list.</p> <pre><code>private List trace(Node parent, Node node) { List path = null; if (null != node) { if (node.data == parent.data) { path = new ArrayList(); } else { path = trace(parent.left, node); if (null == path) { path = trace(parent.right, node); } } if (null != path) { path.add(0, parent); } } return path; } </code></pre>
 

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