코딩테스트

[leetcode] 872. Left-Similar Leafs

nayoon 2024. 6. 11. 23:20

문제

 

/**
 * 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);
    }
}