leetcode100 Same Tree
1 """ 2 Given two binary trees, write a function to check if they are the same or not. 3 Two binary trees are considered the same if they are structurally identical and the nodes have the same value. 4 Example 1: 5 Input: 1 1 6 / \ / \ 7 2 3 2 3 8 [1,2,3], [1,2,3] 9 Output: true 10 Example 2: 11 Input: 1 1 12 / \ 13 2 2 14 [1,2], [1,null,2] 15 Output: false 16 Example 3: 17 Input: 1 1 18 / \ / \ 19 2 1 1 2 20 [1,2,1], [1,1,2] 21 Output: false 22 """ 23 class TreeNode: 24 def __init__(self, x): 25 self.val = x 26 self.left = None 27 self.right = None 28 29 class Solution: 30 def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: 31 if p == None and q == None: 32 return True 33 # bug代码 34 # flag = False 35 # while p and q: 36 # if p.val == q.val: 37 # self.isSameTree(p.left, q.left) 38 # self.isSameTree(q.right, q.right) 39 # flag = True 40 # return flag 41 # 递归注意不用while循环,也应当注意return返回值 42 if p and q and p.val == q.val: 43 return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)