PS/LeetCode
[LeetCode] Symmetric Tree
판교토끼
2020. 5. 1. 00:34
728x90
https://leetcode.com/problems/symmetric-tree/
Symmetric Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
트리의 좌우 대칭을 확인하는 문제이다. 여지껏 푼 easy 단계 문제들 중 로직을 생각하는 데에 가장 오래 걸린 것 같다. 기본적으로 재귀를 사용할 생각은 가지고 있었지만, 좌-우-좌-우와 우-좌-우-좌를 어떻게 구현해야 할지를 몰랐다.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public bool IsSymmetric(TreeNode root) {
return IsMirror(root, root);
}
public bool IsMirror(TreeNode t1, TreeNode t2) {
if(t1==null && t2==null)
return true;
if(t1==null || t2==null)
return false;
return (t1.val == t2.val)
&& IsMirror(t1.right, t2.left)
&& IsMirror(t1.left, t2.right);
}
}
728x90