检查两棵二叉表达式树是否等价
难度:
标签:
题目描述
代码结果
运行时间: 270 ms, 内存: 17.9 MB
/*
* LeetCode 1612: Check If Two Expression Trees are Equivalent
* Given two binary expression trees, return true if the two binary trees are equivalent.
* The equivalent of a binary tree is defined as the trees have the same structure and the same leaf nodes in the same order.
*
* Approach:
* 1. Perform an in-order traversal of both trees.
* 2. Collect leaf nodes in the order they appear using streams.
* 3. Compare the two lists of leaf nodes.
*/
import java.util.*;
import java.util.stream.Collectors;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Solution {
public boolean checkEquivalence(TreeNode root1, TreeNode root2) {
List<Integer> leaves1 = getLeaves(root1);
List<Integer> leaves2 = getLeaves(root2);
return leaves1.equals(leaves2);
}
private List<Integer> getLeaves(TreeNode node) {
if (node == null) return new ArrayList<>();
if (node.left == null && node.right == null) return Arrays.asList(node.val);
return Stream.concat(getLeaves(node.left).stream(), getLeaves(node.right).stream()).collect(Collectors.toList());
}
}
解释
方法:
这个题解采用了深度优先搜索(DFS)来遍历两棵二叉表达式树,同时使用一个数组来统计每个字母节点的出现次数。在第一次DFS遍历时,遍历root1树,对每个字母节点增加其出现次数。在第二次DFS遍历时,遍历root2树,对每个字母节点减少其在数组中的计数。最后,检查数组中的所有值是否都为0,以确定两棵树是否等价。此方法假设表达式树只包含小写字母和'+'节点。
时间复杂度:
O(n)
空间复杂度:
O(h)
代码细节讲解
🦆
在这种方法中,为什么在处理第二棵树时选择将数组中的计数值取反而不是继续使用加法?
▷🦆
这个解法中的DFS是否能够正确处理树中存在的非字母和'+'以外的其他操作符或节点类型?
▷🦆
如果树的结构相同但是节点排列顺序不同(比如左右子树互换),这种方法是否还能判断两棵树等价?
▷🦆
你是如何保证递归过程中不会出现栈溢出错误,尤其是在处理非常深的树时?
▷