說真的,我還真的回答不出,不過到網上找到了資料,希望對你有用。
一般情況下並不能由一箇中綴表示式得到一個唯一的二叉樹,但是若由二叉樹來表示表示式,葉子節點必須是運算元,非葉子節點是運算子,所以能夠確定一個二叉樹:轉化過程如下:
按照優先順序加上括號,得到:( 8 - ( (3 + 5) * ( 5 - (6 / 2) ) ) )
然後從最外層括號開始,依次轉化成二叉樹
1、根是- ,左子樹8,右子樹( (3 + 5) * ( 5 - (6 / 2) ) )
2、右子樹的根*,右子樹的左子樹(3 + 5),右子樹的右子樹( 5 - (6 / 2) )
3、(3 + 5)的根+,左子樹3 ,右子樹5
4、( 5 - (6 / 2) )的根-,左子樹5,右子樹(6 / 2)
5、(6 / 2)的根/,左子樹6,右子樹2
後序遍歷此二叉樹能夠得到該表示式的字尾(逆波蘭)表示形式
程式碼:
[cpp] view plain copy print?
#include “stdio。h”
#include “string。h”
#include “stdlib。h”
#include “stack”
using namespace std;
const char str[] = “3*4+5-2/1”;
struct tree
{
char c;
struct tree* left;
struct tree* right;
};
stack
stack
struct tree* BuildTree()
{
struct tree* node;
for (unsigned int pos = 0; pos < strlen(str); pos++)
{
if (str[pos] - ‘0’ >= 0 && str[pos] - ‘0’ <= 9) //若是數字則作為葉子節點
{
node = (struct tree*) malloc(sizeof(struct tree));
node->c = str[pos];
node->left = NULL;
node->right = NULL;
subTreeStack。push(node);
}
else if (str[pos] == ‘*’ || str[pos] == ‘/’ || str[pos] == ‘+’ || str[pos] == ‘-’)
{
if (!operatorStack。empty() && (str[pos] == ‘+’ || str[pos] == ‘-’)) //若優先順序比棧頂元素低
{
node = (struct tree*) malloc(sizeof(struct tree));
node->c = operatorStack。top();
node->right = subTreeStack。top();
subTreeStack。pop();
node->left = subTreeStack。top();
subTreeStack。pop();
subTreeStack。push(node);
operatorStack。pop();
operatorStack。push(str[pos]);
}
else
operatorStack。push(str[pos]);
}
}
while (!operatorStack。empty())
{
node = (struct tree*) malloc(sizeof(struct tree));
node->c = operatorStack。top();
operatorStack。pop();
node->right = subTreeStack。top();
subTreeStack。pop();
node->left = subTreeStack。top();
subTreeStack。pop();
subTreeStack。push(node);
}
return subTreeStack。top();
}
void PrintTree(struct tree* node)
{
if (node == NULL)
return;
PrintTree(node->left);
PrintTree(node->right);
printf(“%c”, node->c);
}
void main()
{
struct tree* root = BuildTree();
PrintTree(root);
}
在程式中,利用2個棧,高優先順序的符號必然要優先運算,最終會出現在最底端,而低優先順序的符號最後運算,所以出現在樹的最高處。因此,在遇到“+”或者“-”符號的時候,要先將前面的“*”或者“/”計算。考慮到運算元最終會成為葉子節點。
以上內容轉載自http://blog。csdn。net/lwb102063/article/details/52738949