赞
踩
https://leetcode.com/problems/check-if-two-expression-trees-are-equivalent/
给定两个只含'+'
和英文小写字母作为运算数的表达式树,问这两个表达式树所对应的表达式是否等价。等价的含义是两个表达式作为代数式用等号连起来是恒等式。
只需要数一下两个表达式树所含字母的类型、数量都相同即可。代码如下:
public class Solution { public boolean checkEquivalence(Node root1, Node root2) { int[] count = new int[26]; dfs(root1, count, 1); dfs(root2, count, -1); for (int i = 0; i < count.length; i++) { if (count[i] != 0) { return false; } } return true; } private void dfs(Node cur, int[] count, int diff) { if (cur == null) { return; } if (cur.val != '+') { count[cur.val - 'a'] += diff; } dfs(cur.left, count, diff); dfs(cur.right, count, diff); } } class Node { char val; Node left, right; public Node(char val) { this.val = val; } }
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。