Skip to content

Latest commit

 

History

History
34 lines (27 loc) · 914 Bytes

100.Same-Tree.md

File metadata and controls

34 lines (27 loc) · 914 Bytes

100. Same Tree

Difficulty: Easy

URL

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

Solution

Approach 1: Preorder Traversal

The code is shown below:

# 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:
        def preorderTraversal(root1, root2):
            if not root1 and not root2:
                return True
            elif not root1 or not root2 or root1.val != root2.val:
                return False
            else:
                isSame1 = preorderTraversal(root1.left, root2.left)
                isSame2 = preorderTraversal(root1.right, root2.right)
                return isSame1 and isSame2
        return preorderTraversal(p, q)