-4
我很努力地創建一個二進制表達式樹,並沒有找到我正在尋找什麼在線。如何在Java中實現二進制表達式樹?
我很努力地創建一個二進制表達式樹,並沒有找到我正在尋找什麼在線。如何在Java中實現二進制表達式樹?
要實現它,請從包含其自己的子項的結構開始。
public class Node {
public Node left;
public Node right;
public String payload;
Node(String payload){
left = null;
right = null;
this.payload = payload;
}
Node(Node left, Node right, String payload){
this.left = left;
this.right = right;
this.payload = payload;
}
}
然後使用遞歸方法將結果返回給調用的方法。
int total(Node point){
if (point == null) return 0;
switch (point.payload){
case "+": return total(point.left) + total(point.right);
case "-": return total(point.left) - total(point.right);
case "/": return total(point.left)/total(point.right);
case "*": return total(point.left) * total(point.right);
default: return Integer.parseInt(point.payload);
}
}
[Build Binary Expression Tree]的可能重複(http://stackoverflow.com/questions/9136153/build-binary-expression-tree) –