Note that there are some explanatory texts on larger screens.

plurals
  1. POimplementing binary Search tree reconstruction from preOrder array in Java?
    text
    copied!<p>I have followed <a href="http://www.careercup.com/question?id=14419694" rel="nofollow">this idea</a> and this <a href="http://ideone.com/VohnS" rel="nofollow">C++ code</a> to reconstruct binary Search Tree from PreOrder array in Java. I am not reinventing the algorithm, but trying to implement pseudocode. I need help here. I do not get the correct output. The output I get is below the code.</p> <pre><code>public class BinaryTreeMethods { public static void main(String[] args) { int[] arr = {7,5,3,6,9,8,10}; Node newone = CreateFromPreOrder(arr,arr.length); printInorder(newone); System.out.println(); printPreOrder(newone); public static Node CreateFromPreOrder(int[] arr, int length) { if(length==0) return null; Node root = new Node(arr[0]); Stack&lt;Node&gt; s = new Stack&lt;Node&gt;(); s.push(root); for(int i=1; i&lt;length; i++) { Node tmp = new Node(arr[i]); Node next = s.peek(); if(tmp.data &lt; next.data) { next.left = tmp; } else { Node popped = null; while(!s.isEmpty() &amp;&amp; tmp.data &gt; next.data) { popped= s.peek(); s.pop(); } popped.right = tmp; } s.push(tmp); } return root; } public static void printInorder(Node root) { if (root!=null){ printInorder(root.left); System.out.print(" " + root.data); printInorder(root.right); } } class Node { Node left; Node right; int data; public Node(int c){ this(c, null, null); } public Node(int c,Node left, Node right) { this.data = c; this.left=left; this.right=right; } } public static void printInorder(Node root) { if (root!=null){ printInorder(root.left); System.out.print(" " + root.data); printInorder(root.right); } } public static void printPreOrder(Node root) { if (root!=null){ System.out.print(" " + root.data); printInorder(root.left); printInorder(root.right); } } } </code></pre> <p>I do not get the expected output:</p> <pre><code>3 5 7 6 8 9 10 7 3 5 6 8 9 10 </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