Skip to content

Latest commit

 

History

History
29 lines (22 loc) · 815 Bytes

README.md

File metadata and controls

29 lines (22 loc) · 815 Bytes

Same Tree

Problem can be found in here!

# 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

Solution: Recursion

def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
    if not p and not q:
        return True
    elif not p or not q:
        return False

    if p.val != q.val:
        return False

    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)

Time Complexity: O(n), Space Complexity: O(n)