題目要求:(點擊圖片查看)
題目要求:根據前序序列建立表達式數並輸出表達式。
這里可以巧妙的使用遞歸算法解決問題。
這里主要是必須要理清操作符和操作數的關系。所有操作數都為葉子節點,操作符為雙親節點或者根節點。遇到'#'符號停止遞歸。
來自參考:https://blog.csdn.net/qq_41061455/article/details/80553648
源碼與注釋:
#include <bits/stdc++.h> //#include <iostream> //#include <stdio.h> using namespace std; string s; typedef struct Node{ int data; struct Node* left; struct Node* right; }Node; void Build(Node* &tree){//建立二叉樹 cin>>s; int i=0,sn=0,len=0; if(s[0]=='#') tree=NULL; //空葉子 else{ //節點操作判斷 if(s[0]=='+') sn=-1; else if(s[0]=='-') sn=-2; else if(s[0]=='*') sn=-3; else if(s[0]=='/') sn=-4; else{ //葉子節點操作數計算 len=s.size(); //printf("%d\n",len); //輸出字符串s的長度 while(i<len){ sn=sn*10+(s[i]-'0'); i++; } } tree=new Node; tree->data=sn; Build(tree->left); //遞歸建立左子樹 Build(tree->right); //遞歸建立右子樹 } } void Print_Tree(Node* tree){ //打印表達式 if(tree){ if(tree->data>=0) printf("%d",tree->data); //如果遇到葉子節點直接輸出 else{ printf("("); //打印左括號 Print_Tree(tree->left); //打印左子樹 if(tree->data==-1) printf("+"); //打印操作符 else if(tree->data==-2) printf("-"); else if(tree->data==-3) printf("*"); else if(tree->data==-4) printf("/"); Print_Tree(tree->right); //打印右子樹 printf(")"); //打印右括號 } } } int main() { //char ch; while(cin>>s) //輸入string字符串,默認空格結束 { //cout<<s; int i=0,sn=0,len=0; if(s[0]=='+') sn=-1; //操作符判斷 else if(s[0]=='-') sn=-2; else if(s[0]=='*') sn=-3; else if(s[0]=='/') sn=-4; else{ //操作數判斷 len=s.size(); //printf("%d\n",len); while(i<len){ sn=sn*10+(s[i]-'0'); i++; } } Node* tree=new Node; tree->data=sn; //葉子節點 Build(tree->left); //遞歸建立左子樹 Build(tree->right); //遞歸建立右子樹 Print_Tree(tree); //打印表達式 printf("\n"); //輸出空行 } return 0; }

