[Algorithm] Leecode_ 100. Same Tree

JAsmine_log·2024년 8월 17일
0

100. 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:

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

Example 2:

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

Example 3:

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

Constraints:

  • The number of nodes in both trees is in the range [0, 100].
  • -10^4 <= Node.val <= 10^4

Code

C++

  • 두 트리 노드가 모두 nullptr인 경우, 동일한 구조로 간주
  • 두 트리 노드 중 하나만 nullptr인 경우, 구조가 다르므로 false
  • 현재 노드의 값이 동일한지 확인
  • 왼쪽 자식 노드 비교
  • 오른쪽 자식 노드 비교
  • 두 자식 노드 모두 동일해야 전체 트리가 동일함
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q)
    {
        if (p == nullptr && q == nullptr)
        {
            return true;
        }

        if (p == nullptr || q == nullptr)
        {
            return false;
        }

        if (p->val != q->val)
        {
            return false;
        }

        bool isLeftSame = isSameTree(p->left, q->left);

        bool isRightSame = isSameTree(p->right, q->right);

        return isLeftSame && isRightSame;
    }
};
profile
Everyday Research & Development

0개의 댓글