재귀로 풀이.
/**
* 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);
}
}
iteration으로도 풀어봐야지