본문 바로가기
Problem Solving/LeetCode

[LeetCode] 872. Leaf-Similar Trees - Java

by graycode 2026. 10. 30.

• 문제 링크

 

Leaf-Similar Trees - LeetCode

Can you solve this real interview question? Leaf-Similar Trees - Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a leaf value sequence. [https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/16/tree.png

leetcode.com

 

• 풀이 코드

import java.util.ArrayList;
import java.util.List;

public class Solution {

    public boolean leafSimilar(TreeNode root1, TreeNode root2) {
        List<Integer> a = new ArrayList<>(), b = new ArrayList<>();
        inorder(root1, a);
        inorder(root2, b);

        return a.equals(b);
    }

    private void inorder(TreeNode node, List<Integer> list) {
        if (node.left == null && node.right == null) {
            list.add(node.val);
            return;
        }

        if (node.left != null) inorder(node.left, list);
        if (node.right != null) inorder(node.right, list);
    }

}

댓글