๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][LeetCode] 101. Symmetric Tree

๋ฐ˜์‘ํ˜•

[LeetCode] 101. Symmetric Tree

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

๋ฌธ์ œ ์ ‘๊ทผ

๋ฃจํŠธ ๋…ธ๋“œ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์™ผ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์™€ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๊ฐ€ ๋Œ€์นญ์ธ์ง€๋ฅผ ํŒŒ์•…ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค.
BFS์ฒ˜๋Ÿผ ํ๋ฅผ ์ด์šฉํ•ด์„œ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ ํ’€๋ ค๊ณ  ํ–ˆ์œผ๋‚˜, ๋ญ”๊ฐ€ ์ž˜ ์•ˆ๋˜์„œ ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ–ˆ๋‹ค.
์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ์˜ ๋…ธ๋“œ๋ฅผ ์žฌ๊ท€ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ๋น„๊ต
๋‚˜์˜ฌ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜ 4๊ฐ€์ง€
1. ์–‘์ชฝ ๋…ธ๋“œ๊ฐ€ ๋ชจ๋‘ null์ธ ๊ฒฝ์šฐ(์•„๋ฌด ๋ฌธ์ œ ์—†์ด ๋๊นŒ์ง€ ํŠธ๋ฆฌ๋ฅผ ์ˆœํšŒ ํ—€์œผ๋ฏ€๋กœ true)
2. ํ•œ์ชฝ ๋…ธ๋“œ๋งŒ null์ธ ๊ฒฝ์šฐ(๋น„๋Œ€์นญ์ด๋ฏ€๋กœ false)
3. ์–‘์ชฝ ๋…ธ๋“œ์˜ ๊ฐ’์ด ๋‹ค๋ฅธ ๊ฒฝ์šฐ(๋น„๋Œ€์นญ์ด๋ฏ€๋กœ false)
4. ์–‘์ชฝ ๋…ธ๋“œ์˜ ๊ฐ’์ด ๊ฐ™์€ ๊ฒฝ์šฐ(์ง€๊ธˆ๊นŒ์ง€๋Š” ๋Œ€์นญ์ด๋ฏ€๋กœ ์ถ”๊ฐ€์ ์ธ ํŠธ๋ฆฌ ์ˆœํšŒ - ์žฌ๊ท€ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด ์™ผ์ชฝ,์˜ค๋ฅธ์ชฝ ์ž์‹๋“ค์„ ์ˆœํšŒ)
-> ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ๋ชจ๋‘ true์ผ ๊ฒฝ์šฐ๋งŒ ๋Œ€์นญ์ด๋ฏ€๋กœ ๋งˆ์ง€๋ง‰์— return left&&right ์ถ”๊ฐ€

Code

class Solution {
    public boolean isSymmetric(TreeNode root) {
        return checkSymmetric(root,root);
    }
    boolean checkSymmetric(TreeNode leftSide,TreeNode rightSide){
        if(leftSide == null && rightSide == null){
            return true;
        }
        if(leftSide == null || rightSide == null){
            return false;
        }
        if(leftSide.val != rightSide.val) {
            return false;
        }
        boolean left = checkSymmetric(leftSide.left, rightSide.right);
        boolean right = checkSymmetric(leftSide.right, rightSide.left);
        return left && right;
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

์ฒ˜์Œ์— ์™ผ์ชฝ๊ณผ ์˜ค๋ฅธ์ชฝ ์„œ๋ธŒํŠธ๋ฆฌ๋ฅผ queue๋ฅผ ์ด์šฉํ•ด ํ’€๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ ์ž˜ ์•ˆ๋˜์„œ ์‹คํŒจํ–ˆ๋‹ค.
๊ทธ๋ฆฌ๊ณ  ์žฌ๊ท€ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๋Š”๋ฐ ์ฒ˜์Œ์—๋Š” return left && right๊ฐ€ ์—†์–ด์„œ ๊ณ„์† ์‹คํŒจํ–ˆ๊ณ 
๊ณ„์† println์„ ์ด์šฉํ•ด์„œ ์ฐ์–ด์„œ ๊ฑฐ์˜ ์ฐ์–ด์„œ ๋งž์ถ˜ ๊ธ‰์œผ๋กœ ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‹ค ํ•ด๋ณธ ๊ฒƒ ๊ฐ™๋‹ค.

๋ฐ˜์‘ํ˜•