Note that there are some explanatory texts on larger screens.

plurals
  1. POBuild binary expression tree from prefix notation?
    text
    copied!<pre><code>import java.util.ArrayList; import java.util.List; public class ExpressionTree { List&lt;String&gt; expArray = new ArrayList&lt;String&gt;(); ExpressionTreeNode root; ExpressionTreeNode curNode; ExpressionTreeNode left; ExpressionTreeNode right; String element; public ExpressionTree(String prefixExpression) { String[] temp = prefixExpression.split(" "); for (int i = 0; i &lt; temp.length; i++) { expArray.add(temp[i]); } root = createExpressionTree(expArray); System.out.println(root); } private ExpressionTreeNode createExpressionTree(List&lt;String&gt; prefixExpression) { element = prefixExpression.get(0); prefixExpression.remove(0); if (isNumeric(element)) { return new Leaf(Double.parseDouble(element)); } else { left = createExpressionTree(prefixExpression); right = createExpressionTree(prefixExpression); } return new ExpressionTreeNode(left, right, element); } private static boolean isNumeric(String str) { try { double d = Double.parseDouble(str); } catch(NumberFormatException nfe) { return false; } return true; } } </code></pre> <p>That is my code that I want to return an expression tree when given an expression like * + 5 4 – 3 / 2 1. The output i'm getting though is something like this:</p> <pre><code>1 |\ 2 1 /\ 2 1 /\ 2 1 </code></pre> <p>When I'm trying to get:</p> <pre><code> * /\ + - /\ /\ 5 4 3 / /\ 2 1 </code></pre> <p>Any tips? Why are the only elements of my tree the last two elements of the expression? I feel like I'm missing something obvious.</p>
 

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