打印表达式树
我能够按顺序打印我的表达式树。但我需要能够用括号按顺序打印它。例如 postorder 53+ 应该输出 (5+3)
我目前有:
void printTree(struct TreeNode *tree)
{
if (tree != NULL)
{
if (isalpha(tree->info) || isdigit(tree->info))
cout << "(";
printTree( tree->left);
cout<< tree->info;
printTree(tree->right);
if (isalpha(tree->info) || isdigit(tree->info))
cout << ")";
}
}
但这给了我不正确的输出。如果我输入后缀表达式 62/5+ 它会给我 (6)/(2)+(5)
:(
I am able to print my expression tree in inorder. But I need to be able to print it in inorder with parenthesis. for example postorder 53+ should output (5+3)
I currently have:
void printTree(struct TreeNode *tree)
{
if (tree != NULL)
{
if (isalpha(tree->info) || isdigit(tree->info))
cout << "(";
printTree( tree->left);
cout<< tree->info;
printTree(tree->right);
if (isalpha(tree->info) || isdigit(tree->info))
cout << ")";
}
}
But this gives me incorrect output. If i enter postfix expression 62/5+ it gives me (6)/(2)+(5)
:(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要区分叶节点和非叶节点。只有非叶节点才用括号括起来。
You need to distinguish between leaf nodes and non-leaf nodes. Only non-leaf nodes are enclosed in parantheses.
尝试反转决定是否应打印括号的
if
条件:或者可能更好:
其中适当定义了
isoperator
以区分运算符和操作数。Try reversing the
if
conditions that decide whether the parentheses should be printed :Or probably even better :
where
isoperator
is appropriately defined to distinguish operators from operands.