풀이 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;
};
'알고리즘 > BFS & DFS' 카테고리의 다른 글
프로그래머스 - 표현 가능한 이진트리 (JavaScript) (0) | 2023.04.12 |
---|---|
프로그래머스 - 숫자 변환하기 (JavaScript) (0) | 2023.03.19 |
프로그래머스 - 단어 변환 (JavaScript) (0) | 2023.02.20 |
프로그래머스 - 네트워크 (JavaScript) (1) | 2023.02.17 |
백준 1260번 - DFS와 BFS (Python) (0) | 2023.02.17 |