我正在努力创建一个二元表达式树,并且还没有找到我在网上寻找的确切内容。
答案 0 :(得分:1)
要实现它,请从包含自己子节点的结构开始。
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);
}
}