872. Leaf-Similar Trees
難易度
Easy
アプローチ
DFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public ArrayList<Integer> arrayList1;
public ArrayList<Integer> arrayList2;
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
arrayList1 = new ArrayList<>();
arrayList2 = new ArrayList<>();
dfs1(root1);
dfs2(root2);
if (arrayList1.size() != arrayList2.size()) {
return false;
}
for (int i = 0; i < arrayList1.size(); i++) {
if (arrayList1.get(i).intValue() != arrayList2.get(i).intValue()) {
return false;
}
}
return true;
}
public void dfs1(TreeNode root){
if(root == null){
return;
}
dfs1(root.left);
dfs1(root.right);
if(root.left == null && root.right == null){
arrayList1.add(root.val);
}
}
public void dfs2(TreeNode root){
if(root == null){
return;
}
dfs2(root.left);
dfs2(root.right);
if(root.left == null && root.right == null){
arrayList2.add(root.val);
}
}
}