golang面向对象之--二叉表达式树

运行效果

$ ./expression-tree

Input Expression:     [1 + 23 * 1 - 12 * ( 4 + 2 * 5 )]
Caculate Result:     -144
Prefix Expression:     - + 1 * 23 1 * 12 + 4 * 2 5
Infix Expression:     1 + 23 * 1 - 12 * 4 + 2 * 5
Suffix Expression:     1 23 1 * + 12 4 2 5 * + * -

一个简单的结构图

expression-tree

关于面向对象

  1. interface定义方法

    type BinaryTree interface {
        setLeft(node Node)
        setRight(node Node)
        PrefixExpression() string
        SuffixExpression() string
        NifixExpression() string
    }
    
  2. struct管理数据

    type OperateNode struct {
        operate string
        left    Node
        right   Node
    }
    
  3. 需要改变对象定义指针类型的方法

    func (on *OperateNode) setLeft(node Node) {
        on.left = node
    }
    
  4. 不需要改变对象则定义对象类型的方法

    func (on OperateNode) getName() string {
        return on.operate + " "
    }
    
  5. 赋值给接口用指针类型总是正确的

    func CreateOperateNode(v string) (node BinaryTree) {
        switch v {
        case "+":
            return &Add{OperateNode{"+", nil, nil}}
        case "-":
            return &Subtraction{OperateNode{"-", nil, nil}}
    
        ...
    

代码在这里