[코테 풀이] Symmetric Tree

시내·2024년 6월 6일

Q_101) Symmetric Tree

출처 : https://leetcode.com/problems/symmetric-tree/

Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

/**
 * 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) {
        return comp(root.left, root.right);
    }

    public boolean comp(TreeNode first, TreeNode second) {
        if (first == null && second == null) return true;
        if (first == null || second == null) return false;
        if (first.val == second.val) {
            return comp(first.right, second.left) && comp(first.left, second.right);
        }
        return false;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글