LeetCode ❀ 100. Same tree/python implementation of tree traversal

topic:

Given the sum of the root nodes of two binary trees  p ,  q write a function to test whether the two trees are the same.

Two trees are considered identical if they are structurally identical and have nodes with the same values.

Example 1:

输入:p = [1,2,3], q = [1,2,3]
输出:true

 Example 2:

输入:p = [1,2], q = [1,null,2]
输出:false

 Example 3:

输入:p = [1,2,1], q = [1,1,2]
输出:false

answer:

Direct recursion, first write the exit condition

  1. Handle the case where q and p have null values:

                                False when one is empty and the other is not empty, True when both are empty

  1. Handle the case where both q and p are non-empty:

                                When the two non-null values ​​are different, False is returned directly. If the two values ​​​​are the same, you need to enter the next recursion.

We need to be clear that there is only one case where we need to perform the next round of recursion, that is, when the values ​​​​are the same, we write them directly into return. When both have values, we consider using != separately. When one party has no value or both parties have no value, != cannot be used for comparison, then we write another line if (q==None or p==None): return p ==q to compare

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if(q==None or p==None): return p==q
        if(q.val != p.val): return  False
        return self.isSameTree(q.left,p.left) and self.isSameTree(q.right,p.right)

Guess you like

Origin blog.csdn.net/qq_42395917/article/details/126649514
Recommended