[LeetCode] 101. Symmetric Tree

Lucid·2021년 2월 23일
1
post-thumbnail

문제

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

문제 접근 및 풀이

root 노드를 기준으로 대칭을 이루는 것을 확인하는 문제로, 100번 문제와 거의 동일한 문제 100번 문제 풀이에서 크게 다르지 않았다.
하지만 거울에 비치는 것처럼 대칭이어야 하니까 left와 right를 바꾸어 확인해주면 된다.

결과

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */

const isSymmetricLeftRight = (left, right) => {
    if(left===null && right===null) return true;
    if((left !== null && right === null) || (left === null && right !== null)) return false;
    if(left.val !== right.val) return false;
    
    return isSymmetricLeftRight(left.left, right.right) && isSymmetricLeftRight(left.right, right.left);
}

const isSymmetric = (root) =>{
    if(!root) return true;
    return isSymmetricLeftRight(root.left, root.right);
};

사담

초기에 처리해줄수 있는 예외사항들을 먼저 처리해주면 런타임이 훨씬 적게 든다.
ex) root가 null일때

profile
Find The Best Solution 😎

0개의 댓글