Data Structures, Algorithms, & Applications in Java
Chapter 12, Exercise 39
We make the same assumptions as made in Exercise 37.
The conversion is done by first constructing the binary tree form of the
expression as in Exercise 37 and then performing an inorder traversal.
The code is given below.
public class ConvertPrefixToInfix
{
static StringBuffer infixForm;
public static String convertPrefixToInfix(String expression)
{
infixForm = new StringBuffer();
// creates a binary tree from the prefix expression
BinaryTreeNode root =
PrefixToBinaryTree.prefixToBinaryTree(expression);
// fully-parenthesised inorder traversal of the treee
inOrder(root);
return (infixForm.toString());
}
// performs a fully-parenthesised inorder traversal of the tree
public static void inOrder(BinaryTreeNode t)
{
if (t != null)
{
// left child
infixForm.append("(");
inOrder(t.leftChild);
// visit current node
infixForm.append((String)t.element);
// right child
inOrder(t.rightChild);
infixForm.append(")");
}
}
}