반응형
Recent Posts
Notice
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- greedy
- recursion
- priority queue
- PCCP
- 재귀함수
- coding
- 우선순위 큐
- DP
- string
- leetcode
- ArrayList
- hashset
- 리트코드
- 브루트포스
- Array
- 부분배열
- HashMap
- Algorithm
- two pointers
- binary tree
- programmers
- dfs
- 깊이우선탐색
- 알고리즘
- Java
Archives
- Today
- Total
지식창고
[Java] LeetCode 100. Same Tree 본문
728x90
반응형
[Java] LeetCode 100. Same Tree
문 제 :
이진트리 p, q가 두 개 주어진다.
p, q가 똑같이 생긴 이진트리인지 구별해라.
/**
* 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;
* }
* }
*/
Example )
Input: p = [1,2,3], q = [1,2,3]
Output: true
////////////////////////////////
Input: p = [1,2], q = [1,null,2]
Output: false
접 근 :
두 Tree의 모양과 값을 확인하고 재귀적으로 접근.
해 결 :
두 Tree가 모두 null이면 true
둘 중에 하나만 null이면 다른 모양이므로 false
값이 달라도 다른 트리이므로 false
현재 p, q노드의 자식노드들을 위와 같은 식으로 같은지 비교한다. (재귀적)
두 Tree가 모두 비어있으면 true
if(p == null && q == null) return true;
두 Tree 중 하나의 Tree만 비어 있다면 다른 모양이므로 false
두 Tree의 값이 달라도 false
if(p == null || q == null) return false;
if(p.val != q.val) return false;
현재 p, q노드의 자식노드들을 위와 같은 식으로 같은지 비교
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
결 과 :
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
else if(p == null || q == null) return false;
if(p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}
728x90
반응형
'Algorithm > Leetcode' 카테고리의 다른 글
[Java] LeetCode 1061. Lexicographically Smallest Equivalent String (0) | 2023.01.14 |
---|---|
[Java] LeetCode 101. Symmetric Tree (1) | 2023.01.10 |
[Java] LeetCode 144. Binary Tree Preorder Traversal (0) | 2023.01.09 |
[Java] LeetCode 149. Max Points on a Line (0) | 2023.01.09 |
[Java] LeetCode 452. Minimum Number of Arrows to Burst Balloons (0) | 2023.01.06 |
Comments