我能够按顺序打印我的表达式树。但我需要能够用括号按顺序打印它。例如后序 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)
:(
最佳答案
需要区分叶节点和非叶节点。只有非叶节点包含在括号中。
bool isLeaf(struct TreeNode* tree) {
return tree->left == 0 && tree->right == 0;
}
void printTree(struct TreeNode* tree) {
if (tree != NULL) { // this test could be omitted if the printed tree is not empty
if (isLeaf(tree)) {
cout << tree->info;
}
else {
cout << "(";
printTree(tree->left);
cout << tree->info;
printTree(tree->right);
cout << ")";
}
}
}
关于c++ - 打印表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7833567/