+
/ \
1 *
/ \
5 6
这样的。要返回1+(5*6)
struct TreeNode { TreeNode * left, *right; string val; TreeNode(string i) :val(i), left(NULL), right(NULL){} }; bool IsOperator(const string & c) { if (c.length() > 1 || (c[0] >= ‘0‘ && c[0] <= ‘9‘)) { return false; } return true; } string ExpressionTreeToString(TreeNode * node) { if (node == NULL) return ""; string ret = node->val; if (IsOperator(node->val)) { if (node->left) { if (IsOperator(node->left->val)) { ret.insert(0, "(" + ExpressionTreeToString(node->left) + ")"); } else { ret.insert(0, ExpressionTreeToString(node->left)); } } if (node->right){ if (IsOperator(node->right->val)) { ret += "(" + ExpressionTreeToString(node->right) + ")"; } else { ret += ExpressionTreeToString(node->right); } } } return ret; }
时间: 2024-10-06 16:36:33