Problem Solving/LeetCode

Today's Challenge

fabichoi 2023. 1. 10. 23:45

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

복잡하게 트리 순회를 쭉 했는데 계속 테스트 케이스에서 틀려서 솔루션 참고.
재귀로 풀면 간단히 풀림.

def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
    if not p and not q:
        return True
    if p and q and p.val == q.val:
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
    else:
        return False
반응형