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.
제한 사항
- The number of nodes in both trees is in the range [0, 100].
- -104 <= Node.val <= 104
입출력 예
input | output |
p = [1, 2, 3] , q = [1, 2, 3] | True |
p = [1, 2] , q = [1, null, 3] | False |
p = [1, 2, 1] , q = [1, 1, 2] | False |
Python 코드
Python 8ms code
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSameTree(self, p, q):
if not p and not q:
return True
if not p or not q:
return False
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
- isSameTree( )는 왼쪽의 서브 트리와 오르른쪽의 서브트리가 동일한지를 판단하는 재귀함수
* 참고 링크 : https://velog.io/@wisepine/Leetcode-Same-Tree
C++ 코드
C ++ 100% 0ms code
- String으로 바꾸지 않고 맨 뒤의 값과 맨 앞의 값을 비교하면서 푼 코드
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) // if the two nodes are empty nodes, return true
return true;
else if((p == NULL && q != NULL) || (p != NULL && q == NULL)) // if only one of the nodes from p and q is emtpy, 2 trees are not equal
return false;
else
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
// First we compare the values in each node from p and q. Then, use a recursive method, call isSameTree function with left nodes of p and q as parameters. Do the same for the right nodes.
}
};
* 참고 링크 : https://leetcode.com/problems/same-tree/discuss/166896/C++-solution-beats-100
출처
'코딩테스트 > Leet Code' 카테고리의 다른 글
[Leet Code] 136. Single Number (0) | 2022.01.13 |
---|---|
[Leet Code] 118. Pascal's Triangle 다시 공부 ★ (0) | 2022.01.13 |
[Leet Code] 15. 3Sum 다시 공부 ★ (0) | 2022.01.13 |
[Leet Code] 2. Add Two Numbers 다시 공부 ★ (0) | 2022.01.13 |
[Leet Code] 9. Palindrome Number (0) | 2022.01.04 |