[ C++ ] Printing Appropriate parentheses in Binary Expression Tree? via /r/learnprogramming


[ C++ ] Printing Appropriate parentheses in Binary Expression Tree?

My Code:

 void BinaryExpr::InfixExpression(Node * n) { if ( n != nullptr) { if ( isOperator( n -> element) == true) { if ( precedence ( n -> LeftChild -> element) < precedence ( n -> element) { cout << " ("; } } InfixExpression ( n -> LeftChild); cout << n -> data << " "; InfixExpression ( n -> RightChild); if ( isOperator ( n -> element) == true) { if (precedence ( n -> RightChild -> element) >= precedence ( n -> element)) { cout << " )"; } } } } 

Dont know if anyone can give me a general way to do this or point out what I am doing wrong?

Edit: precedence returns 2 is the element is / or *, 1 for + or -, or 0 for everything else

Submitted July 13, 2017 at 07:40PM by CaptainPeruvian
via reddit http://ift.tt/2ukv44w

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s