You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何完善基于逆波兰表示法的表达式树打印方法?

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.println will 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 void to String so 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() returns true for nodes holding values (numbers) and false for operator nodes.
  • isInternal() returns true for operator nodes and false for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:05:23