[알고리즘]_[LeetCode]- 100. Same Tree

SAPCO·2022년 7월 23일
0

- [Algorithm]

목록 보기
9/13
post-custom-banner

📍 1. 문제

LeetCode - 100. Same Tree

📍 2. 풀이

📌 2-1. 풀이 (reculsive)

(1) 방법

재귀로 풀이.

(2) 코드

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        TreeNode left = root.left;
        TreeNode right = root.right;
        
        return isSame(left, right);
    }
    public boolean isSame(TreeNode left, TreeNode right) {
        if(left == null && right == null) return true;
        if(left == null && right != null
            || right == null && left != null) return false;
        if(left.val != right.val) return false;
        
        boolean outer = isSame(left.left, right.right);
        if(outer == false) return false;
        boolean inner = isSame(left.right, right.left);
        
        if(outer == true && inner == true){
             return true;
        }else {
            return false;
        }
    }
}

정리된 코드

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {

        return isSame(root.left, root.right);
    }
    public boolean isSame(TreeNode left, TreeNode right) {
        if(left == null || right == null) return left==right;
        if(left.val != right.val) return false;
        
        return isSame(left.left, right.right) && isSame(left.right, right.left);
    }
}

(3) 결과

📍 3. 결론

iteration으로도 풀어봐야지

profile
SAP CO
post-custom-banner

0개의 댓글