Binary Tree: are trees the same structurally and by value? DFS recursive without helper isSameTree Python

PHOTO EMBED

Mon Jul 18 2022 22:17:42 GMT+0000 (Coordinated Universal Time)

Saved by @bryantirawan #python #tree #recursion #dfs #neetcode

# 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 
        if not p or not q: return False 
        if p.val != q.val: return False 
        
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
        
content_copyCOPY

Big O(p + q) worst case you have to look at each node's values

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