|
-
July 8th, 2010, 08:30 AM
#1
traversing a binary tree
Hi
I've written the following code for converting Postfix to Infix,it reads a string then reads it letter by letter ,a stack and a Tree is used,and I want to traverse the last object that has poped from the stack,in the following code I used this line:
System.out.println((Character)(((TreeNode)stack.pop()).data));
but it only prints the root of the tree,I tried to traverse it but I don't have any idea,I did sth like this( for traversing another node):
(TreeNode)stack.pop() = ( (TreeNode)stack.pop() ).data;
System.out.println((Character)(((TreeNode)stack.pop()).data));
but it didn't work.
would you plz help me with it.
Here is the code:
import java.util.Scanner;
public class Test
{
public static void main( String args[])
{
Scanner input = new Scanner( System.in );
System.out.printf("Enter your String(in Postfix):\n");
String c = input.nextLine();//read a line of text
Stack stack = new Stack();
int i = 0 ;
while( i < c.length() )
{
char a = c.charAt( i );
if( Character.isLetterOrDigit (a) )
{
System.out.printf("\n%c" , a );
stack.push( new TreeNode( a ) );
}
else if( a == '+' || a == '-' || a == '*' || a == '/' )
{
TreeNode t = new TreeNode( a );
t.insert( 0 , stack.pop() );
t.insert( 1 , stack.pop() );
stack.push( t );
}
i++;
}
(TreeNode)stack.pop() = ( (TreeNode)stack.pop() ).data; //<-----Here is the problem
System.out.println((Character)(((TreeNode)stack.pop()).data));
}
}
Thax
Bita
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|