100. Same Tree | LeetCode Using Python

100. Same Tree | LeetCode Using Python

I demonstrate how to solve the Depth-First Search (DFS) problem on a binary tree, showcasing a recursive approach. Watch as I walk through the steps to explore all nodes efficiently.

I dive into solving the “100. Same Tree” problem from LeetCode using Python. I demonstrate how to use a recursive Depth-First Search (DFS) approach to determine if two binary trees are identical. By systematically comparing each node’s value and their respective subtrees.

Python code:

# 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:
        
        #Recursively solve this:
        
        #if both p and q are none, give us True
        if p is None and q is None:
            return True
        
        #if  p or q is none or the value don't match
        if p is None or q is None or p.val != q.val:
            return False

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

#Time complexity will be O(n) since each node will be visited once
#Space Complexity is O(H) H being the height of the tree

Similar Posts