我可以按顺序打印我的表达式树。但我需要能够在括号内打印它。例如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)
:(
答案 0 :(得分:2)
您需要区分叶节点和非叶节点。只有非叶子节点包含在parantheses中。
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 << ")";
}
}
}
答案 1 :(得分:1)
尝试颠倒决定是否应打印括号的if
条件:
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 << ")";
}
}
或者甚至可能更好:
void printTree(struct TreeNode *tree)
{
if (tree != NULL)
{
if (isoperator(tree->info))
cout << "(";
printTree( tree->left);
cout<< tree->info;
printTree(tree->right);
if (isoperator(tree->info))
cout << ")";
}
}
其中isoperator
被适当地定义以区分运算符和操作数。