반응형
https://leetcode.com/problems/same-tree/
Same Tree - LeetCode
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 same value. Example 1: [https://assets.le
leetcode.com
p와 q를 같은 구조로 탐색해나갑니다.
p 또는 q에서 현재 탐색해야할 노드가 없으면, p와 q 모두 노드가 없어야합니다.
p와 q에서 탐색할 노드가 있으면, 두 값이 같아야합니다.
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(!p || !q) return !p && !q;
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 1443 : Minimum Time to Collect All Apples in a Tree (0) | 2023.01.11 |
---|---|
LeetCode 671 : Second Minimum Node In a Binary Tree (1) | 2023.01.11 |
LeetCode 149 : Max Points on a Line (1) | 2023.01.08 |
LeetCode 134 : Gas Station (0) | 2023.01.08 |
LeetCode 2244 : Minimum Rounds to Complete All Tasks (1) | 2023.01.04 |