Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Same Tree[E,Tree,Depth-First Search,Breadth-First Search,Binary Tree]

eatplaylove 2024. 8. 22. 14:19

https://leetcode.com/problems/same-tree/description/

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].
  • -104 <= Node.val <= 104

간만에 풀어 보는 tree 문제

가보자

 

1. C++

일단 container가 있어야 진전이 있을 거 같아서 C++부터 코드를 짜봤다.

그럼에도 역시 잔실수가 좀 있어서 디버깅하는데 GPT도움을 받았다.

GPT 0 % 코딩은 언제 가능할 것인가..

 

/**
 * 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(p == nullptr && q == nullptr) return true;
        if(p == nullptr || q == nullptr) return false;

        queue<TreeNode*> p1;
        queue<TreeNode*> q1;
        p1.push(p);
        q1.push(q);

        while(!p1.empty()){
            TreeNode* currp = p1.front();
            p1.pop();
            TreeNode* currq = q1.front();
            q1.pop();
            if((currp->val) != (currq->val)) return false;

            if(currp->left){
                if(!currq->left) return false;
                p1.push(currp->left);
                q1.push(currq->left);
            }
            if(currp->right){
                if(!currq->right) return false;
                p1.push(currp->right);
                q1.push(currq->right);
            }
            if(!currp->left){
                if(currq->left) return false;
            }
            if(!currp->right){
                if(currq->right) return false;
            }
        }
        if(!q1.empty()) return false;

        return true;
    }
};

 

2. C

 

모범답안을 보니 굉장히 간단하다..

Recursive하게 풀면 되는구나..

별 삽질을 다 했는데, 의외다 정말!

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
    if(p==NULL && q==NULL) return true;
    else if(p==NULL || q==NULL) return false;
    return (p->val == q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}

 

 

3. Python

 

조잡하게 풀어보기~

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q : return True
        elif not p or not q : return False

        dep = deque()
        deq = deque()

        dep.append(p)
        deq.append(q)

        while dep:
            currp = dep.popleft()
            currq = deq.popleft()
            if currp.val != currq.val : return 0;

            if currp.left :
                if not currq.left : return 0
                dep.append(currp.left)
                deq.append(currq.left)
            if currp.right :
                if not currq.right : return 0
                dep.append(currp.right)
                deq.append(currq.right)
            if not currp.left:
                if currq.left : return 0
            if not currp.right:
                if currq.right : return 0
        
        if deq : return 0

        return 1