zoukankan      html  css  js  c++  java
  • 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)
  • 相关阅读:
    如何查看ubuntu版本
    基于Python与命令行人脸识别项目(系列一)
    问题 B: Curriculum Vitae
    问题 M: 克隆玩具
    1906: 鹊桥相会
    3265: 聪明的矿工
    2363: 完美旗手队列
    2545: 内部收益率
    2544: 台球碰撞
    3272: 公民身份号码
  • 原文地址:https://www.cnblogs.com/yawenw/p/12284797.html
Copyright © 2011-2022 走看看