樹建設前綴表達式
def insert
Insert each token in the expression from left to right:
(0) If the tree is empty, the first token in the expression (must
be an operator) becomes the root
(1) Else if the last inserted token is an
operator, then insert the token as the left child of the last inserted
node.
(2) Else if the last inserted token is an operand, backtrack up the
tree starting from the last inserted node and find the first node with a NULL
right child, insert the token there. **Note**: don't insert into the last inserted
node.
end def
讓我們做一個例子:+ 2 + 1 1
應用(0)。
+
適用(1)。
+
/
2
適用(2)。
+
/\
2 +
適用(1)。
+
/\
2 +
/
1
最後,申請(2)。
+
/\
2 +
/\
1 1
該算法對- */15 - 7 + 1 1 3 + 2 + 1 1
經過測試所以Tree.insert
實現這三個規則。
insert(rootNode, token)
//create new node with token
if (isLastTokenOperator)//case 1
//insert into last inserted's left child
else { //case 2
//backtrack: get node with NULL right child
//insert
}
//maintain state
lastInsertedNode = ?, isLastTokenOperator = ?
評估樹有點有趣,因爲你必須從樹的右下角開始。執行反向post-order遍歷。首先拜訪正確的孩子。
evalPostorder(node)
if (node == null) then return 0
int rightVal = evalPostorder(node.right)
int leftVal = evalPostorder(node.left)
if(isOperator(node.value))
return rightVal <operator> leftVal
else
return node.value
鑑於從前綴表達式構建樹的簡單,我建議使用標準stack algorithm轉換從綴到前綴。在實踐中,您會使用堆棧算法來評估中綴表達式。
你到目前爲止嘗試過什麼?僞代碼在那裏(並且網上有很多實現,無論好壞)。 –
我已經寫了函數來讀取後綴,中綴和前綴順序的樹。我知道有很多例子,但是我找不到我要找的東西。我需要從如何從代數表達式(我的意思是如何表達和測試優先級並存儲值等)開始創建一棵樹。我知道我要求的是基本的,但我只是卡住了。任何鏈接或幫助將不勝感激。謝謝。 – Anila
一般來說,要編寫一個解析器,你需要一個語法。然後有很多種解析器。在網上搜索「遞歸下降」解析器 - 很容易理解如何對它們進行編碼。順便問一下,這是功課嗎? –