题解 | #相逆叶子#
相逆叶子
https://www.nowcoder.com/practice/41c7b0e8710e43ca9f328bf06ea2aff3
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root1 TreeNode类 * @param root2 TreeNode类 * @return bool布尔型 */ public boolean leafSimilar(TreeNode root1, TreeNode root2) { Queue<TreeNode> queue1 = new LinkedList<>(); Queue<TreeNode> queue2 = new LinkedList<>(); queue1.add(root1); queue2.add(root2); ArrayList<Integer> list1 = new ArrayList<>(); ArrayList<Integer> list2 = new ArrayList<>(); while (!queue1.isEmpty()) { int size = queue1.size(); list1.clear(); for (int i = 0; i < size; i++) { TreeNode node = queue1.poll(); if (node != null) { list1.add(node.val); if (node.left != null) { queue1.add(node.left); } if (node.right != null) { queue1.add(node.right); } } } } while (!queue2.isEmpty()) { int size = queue2.size(); list2.clear(); for (int i = 0; i < size; i++) { TreeNode node = queue2.poll(); if (node != null) { list2.add(node.val); if (node.left != null) { queue2.add(node.left); } if (node.right != null) { queue2.add(node.right); } } } } return isEqual(list1, list2); } public boolean isEqual(ArrayList<Integer> list1, ArrayList<Integer> list2) { Collections.reverse(list2); for (int i = 0; i < list1.size(); i++) { if (!list1.get(i).equals(list2.get(i))) { return false; } } return true; } }