📜  从前缀表达构建表达树

📅  最后修改于: 2021-05-28 04:35:51             🧑  作者: Mango

给定一个表示前缀表达式的字符数组a [] 。任务是为表达式构建一个表达式树,然后打印所构建树的中后缀表达式。

例子:

方法:如果字符是操作数,即X,则它将是所需树的叶子节点,因为所有操作数都在表达式树的叶子处。否则,如果字符是运算符且格式为OP XY,则它将是一个内部节点,其中左子节点为expressionTree(X) ,右子节点为expressionTree(Y) ,可以使用递归函数进行求解。

下面是上述方法的实现:

// C program to construct an expression tree 
// from prefix expression
#include 
#include 
  
// Represents a node of the required tree
typedef struct node {
    char data;
    struct node *left, *right;
} node;
  
// Function to recursively build the expression tree
char* add(node** p, char* a)
{
  
    // If its the end of the expression
    if (*a == '\0')
        return '\0';
  
    while (1) {
        char* q = "null";
        if (*p == NULL) {
  
            // Create a node with *a as the data and
            // both the children set to null
            node* nn = (node*)malloc(sizeof(node));
            nn->data = *a;
            nn->left = NULL;
            nn->right = NULL;
            *p = nn;
        }
        else {
  
            // If the character is an operand
            if (*a >= 'a' && *a <= 'z') {
                return a;
            }
  
            // Build the left sub-tree
            q = add(&(*p)->left, a + 1);
  
            // Build the right sub-tree
            q = add(&(*p)->right, q + 1);
  
            return q;
        }
    }
}
  
// Function to print the infix expression for the tree
void inr(node* p) // recursion
{
    if (p == NULL) {
        return;
    }
    else {
        inr(p->left);
        printf("%c ", p->data);
        inr(p->right);
    }
}
  
// Function to print the postfix expression for the tree
void postr(node* p)
{
    if (p == NULL) {
        return;
    }
    else {
        postr(p->left);
        postr(p->right);
        printf("%c ", p->data);
    }
}
  
// Driver code
int main()
{
    node* s = NULL;
    char a[] = "*+ab-cd";
    add(&s, a);
    printf("The Infix expression is:\n ");
    inr(s);
    printf("\n");
    printf("The Postfix expression is:\n ");
    postr(s);
    return 0;
}
输出:
The Infix expression is:
 a + b * c - d 
The Postfix expression is:
 a b + c d - *

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。