Evaluation expression tree

Given the root node, calculate the equation’s value
e.g + +
/ \ /
2 3 - +
2+3=5 / \ /
1 3 2 4 (1-3) + (2+4) = 4

假设是只有叶子节点是数字
下面是 TreeNode的定义。只有正负运算符。

class TreeNode {
  int val;
  char op;
  boolean isOp;
  // @toDo 
  // constructor
}

做法是recursion。比较straightforward.

class Solution {
  public int evaluateExpressionTree(TreeNode root) {
    if (root == null) return 0;
    if (!root.isOp) return root.val;
    int left = evaluateExpressionTree(root.left);
    int right = evaluateExpressTree(root.right);
    return root.op == '+' ? left + right : left - right;
  }
}

你可能感兴趣的:(Evaluation expression tree)