본문 바로가기
LeetCode/코딩 테스트 스터디 3주차

[LeetCode] 101. Symmetric Tree 풀이 (JS)

by inwoo1324 2022. 7. 24.

0. 문제

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

 

Symmetric Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

입력값 이진 트리가 주어지면 그것이 자신의 거울인지 (즉, 중심을 중심으로 대칭인지) 확인하는 문제

Input: root = [1,2,2,3,4,4,3]      Output: true
Input: root = [1,2,2,null,3,null,3]     Output: false

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

var isSymmetric = function(root) {
    return isSameTree(root, root); 
};

function isSameTree(t1, t2) {
    if (t1 === null && t2 === null) return true;
    if (t1 === null || t2 === null) return false;
    return t1.val === t2.val && isSameTree(t1.left, t2.right) && isSameTree(t1.right, t2.left); 
}
Runtime: 85 ms, faster than 75.28% of JavaScript online submissions for Symmetric Tree.
Memory Usage: 44.8 MB, less than 35.36% of JavaScript online submissions for Symmetric Tree.
 

재귀 알고리즘으로 두 트리의 오른쪽 노드와 왼쪽 노드 각각 한 지점씩 검사한다.

각 val 값과 트리의 길이가 동일한지 판별하고

방향을 바꾸어 동일하게 검사하며 다른 부분이 있을 경우 false 를 반환한다.