728x90
반응형
100. Same Tree
LeetCode
https://leetcode.com/problems/same-tree/description/
Same Tree - LeetCode
Can you solve this real interview question? Same Tree - Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the
leetcode.com
Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
두 개의 이진 트리 p와 q의 루트(root)가 주어졌을 때, 두 트리가 같은지 확인하는 함수를 작성하세요.
두 이진 트리는 구조적으로 동일하고 노드의 값이 같을 때 같은 것으로 간주합니다.
Example

Input: p = [1,2,3], q = [1,2,3]
Output: true

Input: p = [1,2], q = [1,null,2]
Output: false

Input: p = [1,2,1], q = [1,1,2]
Output: false
1. 문제 요구사항 분석
두 개의 이진트리가 동일한지 비교
2. 접근 전략
😁 dfs로 풀기
/**
* 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 isSameTree(TreeNode p, TreeNode q) {
// 둘 다 null이면 동일한 값
if (p == null && q == null) return true;
// 둘 중 하나만 null이거나, 값이 다를 경우
if (p == null || q == null || p.val != q.val) return false;
// 현재 노드가 같다면, 왼쪽 자식과 오른쪽 자식을 재귀적으로 확인
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
}728x90
반응형
'프로그래밍 > 알고리즘' 카테고리의 다른 글
| [LeetCode] 56. Merge Intervals (0) | 2026.06.01 |
|---|---|
| [LeetCode] 268. Missing Number (0) | 2026.05.28 |
| [LeetCode] 53. Maximum Subarray (0) | 2026.05.25 |
| [LeetCode] 2574. Left and Right Sum Differences (0) | 2026.05.19 |
| [LeetCode] 1480. Running Sum of 1d Array (0) | 2026.05.18 |