题解 | #相逆叶子#
相逆叶子
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) { // write code here List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); collectLeaf(root1, list1, "left"); collectLeaf(root2, list2, "right"); if(list1.size() != list2.size()) return false; for(int i = 0; i < list1.size(); i++){ if(list1.get(i) != list2.get(i)) return false; } return true; } private void collectLeaf(TreeNode root, List<Integer> list, String mark){ if(root == null) return; if(root.left == null && root.right == null) { list.add(root.val); return; } if("left".equals(mark)){ collectLeaf(root.left, list, "left"); collectLeaf(root.right, list, "left"); }else{ collectLeaf(root.right, list, "right"); collectLeaf(root.left, list, "right"); } } }