/**
* 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 List<Integer> leaf1;
public List<Integer> leaf2;
public boolean leafSimilar(TreeNode root1, TreeNode root2) {
leaf1 = new ArrayList<>();
leaf2 = new ArrayList<>();
leaf(root1, 1);
leaf(root2, 2);
return compare();
}
public boolean compare() {
if (leaf1.size() != leaf2.size()) {
return false;
}
for(int i = 0; i < leaf1.size(); i++) {
if (!leaf1.get(i).equals(leaf2.get(i))) {
return false;
}
}
return true;
}
public void leaf(TreeNode root, int index) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
if (index == 1) {
leaf1.add(root.val);
}
if (index == 2) {
leaf2.add(root.val);
}
return;
}
leaf(root.left, index);
leaf(root.right, index);
}
}
'코딩테스트' 카테고리의 다른 글
[leetcode] 1161. Maximum Level Sum of a Binary Tree (0) | 2024.06.14 |
---|---|
[leetcode] 1448. Count Good Nodes in Binary Tree (0) | 2024.06.14 |
[leetcode] 443. String Compression (0) | 2024.06.11 |
[leetcode] 724. Find Pivot Index (1) | 2024.06.09 |
[leetcode] 238. Product of Array Except self (1) | 2024.06.09 |