Sapphire9 개발 일지

풀이 1) recursion

/**
 * 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}
 */
var isSymmetric = function(root) {

    return isSame(root.left, root.right);
};

var isSame = function (leftroot, rightroot) {
    if ((!leftroot && rightroot) || (leftroot && !rightroot) || (leftroot && rightroot && leftroot.val !== rightroot.val))
        return false;

    if (!leftroot && !rightroot)
        return true;

    return isSame(leftroot.left, rightroot.right) && isSame(leftroot.right, rightroot.left);
}

 

풀이 2) stack

/**
 * 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}
 */
var isSymmetric = function(root) {
    
    const stack = [root.left, root.right];
        
    while(stack.length) {
        let currRight = stack.pop();
        let currLeft = stack.pop();
        
        if(currRight === null && currLeft === null)
            continue;
        
        if((currRight === null || currLeft === null) || currRight.val !== currLeft.val)
            return false;
    
        stack.push(currLeft.left, currRight.right, currLeft.right, currRight.left);

    }
    return true;
};

 

풀이 3) queue

/**
 * 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}
 */
 var isSymmetric = function(root) {
    if (!root) return true;
    
    const queue = [root.left, root.right];
    while (queue.length) {
        const currLeft = queue.shift();
        const currRight = queue.shift();

        if (!currLeft && !currRight) continue;

        if ((!currLeft || !currRight) || currLeft.val !== currRight.val) return false;

        queue.push(currLeft.left, currRight.right, currLeft.right, currRight.left);
    }
    return true;
};
profile

Sapphire9 개발 일지

@Sapphire9

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그