题目
解答
class Solution {public void inorder(TreeNode node, List<Integer> values) {if (node == null) {return;}if (node.left == null && node.right == null) {values.add(node.val);return;}inorder(node.left, values);inorder(node.right, values);}public boolean leafSimilar(TreeNode root1, TreeNode root2) {List<Integer> values1 = new LinkedList<>();List<Integer> values2 = new LinkedList<>();inorder(root1, values1);inorder(root2, values2);if (values1.size() != values2.size()) {return false;}for (int i = 0, length = values1.size(); i < length; ++i) {if (values1.get(i) != values2.get(i)) {return false;}}return true;}
}
要点
通过对树的遍历,找到叶子节点,然后按照题目的要求检查两棵树的叶子节点是否一致。