如何完善基于逆波兰表示法的表达式树打印方法?
Completing the Expression Tree Formatter
Your current code has a couple of key issues preventing it from working correctly:
- The method is
void, so you can't recursively build and concatenate string segments for internal nodes. - Directly printing leaves with
System.out.printlnwill output each leaf on a new line instead of integrating it into the full expression string.
Here's the corrected implementation that builds the properly formatted expression string recursively:
static String printExpressionTree(TreeNode tmp) { // Handle leaf nodes (return their value as a string) if (tmp.isLeaf()) { return tmp.toString(); // Assumes TreeNode.toString() returns the leaf's value (e.g., "5") } // Handle internal nodes (build the "(left operator right)" format) if (tmp.isInternal()) { StringBuilder sb = new StringBuilder(); sb.append("("); // Add left child expression if present if (tmp.hasLeft()) { sb.append(printExpressionTree(tmp.left)).append(" "); } // Add the operator (from the internal node itself) sb.append(tmp.toString()); // Assumes TreeNode.toString() returns the operator (e.g., "+") // Add right child expression if present if (tmp.hasRight()) { sb.append(" ").append(printExpressionTree(tmp.right)); } sb.append(")"); return sb.toString(); } // Fallback for unexpected node types (adjust based on your TreeNode implementation) return ""; }
Key Improvements & Explanations:
- Return Type Change: Switched from
voidtoStringso we can recursively construct the expression string instead of printing fragments directly. - StringBuilder: Used for efficient string concatenation (avoids creating unnecessary intermediate string objects).
- Recursive Structure: For each internal node, we wrap the left child's expression, the operator, and the right child's expression in parentheses exactly as specified.
- Flexibility: Returns the full expression string, so you can print it, store it, or manipulate it further:
// To print the full expression tree: TreeNode root = ...; // Your expression tree root node System.out.println(printExpressionTree(root));
Assumptions About Your TreeNode Class:
isLeaf()returnstruefor nodes holding values (numbers) andfalsefor operator nodes.isInternal()returnstruefor operator nodes andfalsefor leaves.hasLeft()/hasRight()correctly indicate if a child node exists.toString()returns the appropriate value: the number as a string for leaves, and the operator (e.g., "+", "-", "*", "/") as a string for internal nodes.
If your TreeNode class uses different methods to access values (like getValue() instead of toString()), just adjust those parts accordingly. For example, if leaves have a getValue() method returning a number, replace tmp.toString() with String.valueOf(tmp.getValue()).
内容的提问来源于stack exchange,提问作者Beatrice.Pierce
相关产品推荐
相关产品推荐

