用于构造后缀表达式的表达式树的 C++ 程序


表达式树基本上是一种用于表示表达式的二叉树。在表达式树中,节点对应于运算符,每个叶节点对应于操作数。这是一个用于构造后缀表达式中表达式树的 C++ 程序,采用中序、前序和后序遍历方式。

算法

Begin
   Function r() has a character variable as parameter.
      If the characters are + or - or * or / then
         Return will be -1
      If the characters are from A to Z then
         Return will be 1.
      If the characters are from a to z then
         Return will be 1.
      Else
         Return -100.
   Function construct_expression_tree() to construct the expression tree
   Function push() to push values in the stack
   Function pop() to pop values from the stack
   Function preOrder() for pre-order traversal
   Function inOrder() for in-order traversal
   Function postOrder() for post-order traversal 
End.

示例代码

 实时演示

#include <iostream>
using namespace std;
struct n {
   char d;
   n *l;
   n *r;
};
char pf[50];
int top = -1;
n *a[50];
int r(char inputch) {
   if (inputch == '+' || inputch == '-' || inputch == '*' || inputch== '/')
      return (-1);
   else if (inputch >= 'A' || inputch <= 'Z')
      return (1);
   else if (inputch >= 'a' || inputch <= 'z')
      return (1);
   else
      return (-100);
}
void push(n *tree) {
   top++;
   a[top] = tree;
}
n *pop() {
   top--;
   return (a[top + 1]);
}
void construct_expression_tree(char *suffix) {
   char s;
   n *newl, *p1, *p2;
   int flag;
   s = suffix[0];
   for (int i = 1; s != 0; i++) {
      flag = r(s);
      if (flag == 1) {
         newl = new n;
         newl->d = s;
         newl->l = NULL;
         newl->r = NULL;
         push(newl);
      } else {
         p1 = pop();
         p2 = pop();
         newl = new n;
         newl->d = s;
         newl->l = p2;
         newl->r = p1;
         push(newl);
      }
      s = suffix[i];
   }
}
void preOrder(n *tree) {
   if (tree != NULL) {
      cout << tree->d;
      preOrder(tree->l);
      preOrder(tree->r);
   }
}
void inOrder(n *tree) {
   if (tree != NULL) {
      inOrder(tree->l);
      cout << tree->d;
      inOrder(tree->r);
   }
}
void postOrder(n *tree) {
   if (tree != NULL) {
      postOrder(tree->l);
      postOrder(tree->r);
      cout << tree->d;
   }
}
int main(int argc, char **argv) {
   cout << "Enter Postfix Expression : ";
   cin >> pf;
   construct_expression_tree(pf);
   cout << "\nIn-Order Traversal : ";
   inOrder(a[0]);
   cout << "\nPre-Order Traversal : ";
   preOrder(a[0]);
   cout << "\nPost-Order Traversal : ";
   postOrder(a[0]);
   return 0;
}

输出

Enter Postfix Expression : 762*+6+
In-Order Traversal : 7+6*2+6
Pre-Order Traversal : ++7*626
Post-Order Traversal : 762*+6+

更新于: 2019 年 7 月 30 日

2000+ 次观看

启动你的 职业

通过完成课程获得认证

开始
广告