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
입력값 이진 트리가 주어지면 그것이 자신의 거울인지 (즉, 중심을 중심으로 대칭인지) 확인하는 문제
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 를 반환한다.
'LeetCode > 코딩 테스트 스터디 3주차' 카테고리의 다른 글
[LeetCode] 100. Same Tree 풀이 (JS) (0) | 2022.07.24 |
---|---|
[LeetCode] 15. 3Sum 풀이 (JS) (0) | 2022.07.24 |
[LeetCode] 88. Merge Sorted Array 풀이 (JS) (0) | 2022.07.24 |
[LeetCode] 12. Integer to Roman 풀이 (JS) (0) | 2022.07.24 |
[LeetCode] 83. Remove Duplicates from Sorted List 풀이 (JS) (0) | 2022.07.24 |