Same Tree

Problem

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:

Same Tree_第1张图片

Input: p = [1,2,3], q = [1,2,3]
Output: true

Example 2:

Same Tree_第2张图片

Input: p = [1,2], q = [1,null,2]
Output: false

Example 3:

Same Tree_第3张图片

Input: p = [1,2,1], q = [1,1,2]
Output: false

Intuition

The problem is to determine whether two binary trees are the same or not. Two binary trees are considered the same if they are structurally identical, and corresponding nodes have the same values. The intuition is to perform a recursive comparison of nodes, checking if the current nodes are equal and then recursively comparing their left and right subtrees.

Approach

Base Cases:

If both trees are empty (None), return True since they are structurally identical.
If only one of the trees is empty, return False since they cannot be the same.
Node Value Comparison:

Compare the values of the current nodes in both trees.
If the values are not equal, return False.
Recursive Comparison:

Recursively compare the left and right subtrees of the current nodes.
The result of the comparison for the left and right subtrees should be True for the overall trees to be considered the same.
Return Result:

Return the result of the recursive comparison.

Complexity

  • Time complexity:

The time complexity is O(n), where n is the number of nodes in the binary tree. Each node is visited exactly once during the recursive traversal.

  • Space complexity:

The space complexity is O(h), where h is the height of the binary tree. This is due to the depth of the recursive call stack. In the average case, for a balanced binary tree, the height is O(log n), making the space complexity O(log n). However, in the worst case of an unbalanced tree, the height could be O(n), resulting in a space complexity of O(n).

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:
        if not p and not q:
            return True

        if not p or not q:
            return False

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

        left = self.isSameTree(p.left, q.left)
        right = self.isSameTree(p.right, q.right)

        return left and right

你可能感兴趣的:(leetcode算法学习,算法)