c++ - 打印表达式树

标签 c++ tree expression

我能够按顺序打印我的表达式树。但我需要能够用括号按顺序打印它。例如后序 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/

相关文章:

c++ - 平衡二叉树编码

c# - 使用递归过滤树

javascript - 命名函数在 JavaScript 中被低估了吗?

c++ - 服务器内存管理

c++ - 如何检测使用 opencv 绘制的多边形轮廓?

java - 将二叉树转换为 List<List<Node>>

bash - Shell:如何计算具有两个以上操作数的算术表达式

json - 使用 Newtonsoft.Json.NET 搜索 JSON 根对象的正确 JsonPath 表达式是什么?

c++ - 使用 Windows api 和 C++,我如何从硬盘驱动器加载一个 exe 并在它自己的线程中运行它?

c++ - printf 的格式化缓冲区在哪里?