'Binary tree not clearing with each loop iteration
I am using a binary tree to convert prefix expression into infix, and then solving them. That part works fully.
My issue is the input loop I set up is adding on the new expression to the old tree, resulting in an error. I have tried clearing the linked list, and manually created a method to empty out the tree. But every time, the output I have is showing the new expression appended to the previous one, rather than creating a whole new tree.
public static void main(final String[] args) {
Scanner listener = new Scanner(System.in);
System.out.println();
System.out.println("Enter a prefix expression Separated by space!! (Enter 'done' to end): ");
String line = listener.nextLine();
while(!line.equalsIgnoreCase("done")){
System.out.println(line);
if(line.length()<=1){ System.out.println("Invalid expression"); listener.close(); return;}
instances(line);
line = new String();
line = listener.nextLine();
}
listener.close();
}
public static void instances(String input){
System.out.println("The input expression was \n\t"+ input +"\n");
String[] in = input.split(" ");
LinkedList<String> queue = new LinkedList<>(Arrays.asList(in));
TreeNode root = new TreeNode(queue, null);
System.out.println("Expression as infix: ");
inOrder(root);
System.out.println(infix_string);
String[] infix = infix_string.split(" ");
Stack infix_stack = new Stack(infix);
System.out.print("\t" + infix_stack + " = ");
infix_stack.answer();
System.out.println();
System.out.println("Enter a prefix expression Separated by space!! (Enter 'done' to end): ");
queue.clear();
clearTree(root);
}
public static void clearTree(TreeNode root){
if(root != null){
clearTree(root.left);
clearTree(root.right);
root=null;
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

