개발/코딩테스트

[Leetcode] 101. Symmetric Tree #Easy #Java

brobro332 2025. 3. 11. 20:44
반응형
문제
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
예제 1
Input: root = [1,2,2,3,4,4,3]
Output: true

예제 2
Input: root = [1,2,2,null,3,null,3]
Output: false
제약조건
✅ The number of nodes in the tree is in the range [1, 1000]. 

✅ -100 <= Node.val <= 100

 
문제풀이

/**
 * 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 boolean isSymmetric(TreeNode root) {
        // 1. 빈 노드가 주어졌다면 참 처리
        if (root == null) return true;

        // 2. 반환
        return dfs(root.left, root.right);
    }

    /**
     * DFS
     */
    public boolean dfs(TreeNode leftChildNode, TreeNode rightChildNode) {
        // 1. 유효성 체크
        if (leftChildNode == null && rightChildNode == null) return true;
        if (leftChildNode == null || rightChildNode == null) return false;
        if (leftChildNode.val != rightChildNode.val) return false;

        // 2. DFS 처리
        return dfs(leftChildNode.left, rightChildNode.right) && dfs(leftChildNode.right, rightChildNode.left);
    }
}
  • DFS로 풀었는데, BFS로도 풀릴 것 같다.
트리 별로 안 좋아하는데 문제를 순차적으로 풀어서 그런가 요즘 트리 문제만 풀고 있다. 😂
하긴 좋아하는 문제 유형이 딱히 있지도 않은 듯.

 

이미지 출처

[김은우의 에듀테크 트렌드 따라잡기] 코딩 교육 사이트 LeetCode가 보여주는 코딩교육의 핵심

[김은우의 에듀테크 트렌드 따라잡기] 코딩 교육 사이트 LeetCode가 보여주는 코딩교육의 핵심

edu.chosun.com