C++ 打印表达式树
我可以按顺序打印我的表达式树。但我需要能够用括号按顺序打印出来。例如,postorder 53+应输出(5+3) 我目前有:C++ 打印表达式树,c++,tree,expression,C++,Tree,Expression,我可以按顺序打印我的表达式树。但我需要能够用括号按顺序打印出来。例如,postorder 53+应输出(5+3) 我目前有: void printTree(struct TreeNode *tree) { if (tree != NULL) { if (isalpha(tree->info) || isdigit(tree->info)) cout << "("; printTree( tree->left);
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打印树(结构树节点*tree)
{
如果(树!=NULL)
{
if(isalpha(树->信息)| isdigit(树->信息))
不能离开);
库廷福;
打印树(树->右);
if(isalpha(树->信息)| isdigit(树->信息))
cout如果决定是否打印括号的条件为
,请尝试反转该条件:
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打印树(结构树节点*tree)
{
如果(树!=NULL)
{
如果(!(isalpha(树->信息)| isdigit(树->信息)))
不能离开);
库廷福;
打印树(树->右);
如果(!(isalpha(树->信息)| isdigit(树->信息)))
法院信息)
不能离开);
库廷福;
打印树(树->右);
if(等运算符(树->信息))
cout您需要区分叶节点和非叶节点。只有非叶节点包含在paranethes中
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 << ")";
}
}
}
bool isLeaf(结构树节点*tree){
返回树->左==0&&tree->右==0;
}
无效打印树(结构树节点*树){
如果(tree!=NULL){//如果打印的树不是空的,则可以省略此测试
if(岛(树)){
计算机信息;
}
否则{
不能离开);
计算机信息;
打印树(树->右);
库特@Tomalak:
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 << ")";
}
}
}