코딩테스트 준비/leetcode

100. Same Tree [Easy]

MAKGA 2021. 6. 16. 23:37
320x100

출처: https://leetcode.com/problems/same-tree/submissions/

 

Same 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

 

두 트리가 동일한지 체크하는 문제였는데, nullptr 체크를 if문 한 개로 하려다가 에러 먹음...ㅠㅠ

source
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (nullptr == p && nullptr == q) {
            return true;
        }
        
        if ((nullptr == p && nullptr != q) ||
           (nullptr != p && nullptr == q)) {
            return false;
        }
        
        if (p->val != q->val) {
            return false;
        }
        
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};

320x100

'코딩테스트 준비 > leetcode' 카테고리의 다른 글

111. Minimum Depth of Binary Tree  (0) 2021.07.17
98. Validate Binary Search Tree [Medium]  (0) 2021.06.18
7. Reverse Integer [Easy]  (0) 2021.06.14
12. Integer to Roman [Medium]  (0) 2021.06.14
113. Path Sum II [Medium]  (0) 2021.06.14