LeetCode | 0100. Same Tree 相同的树【Python】

阳光穿透心脏的1/2处 2023-02-20 15:57 95阅读 0赞

LeetCode 0100. Same Tree 相同的树【Easy】【Python】【二叉树】

Problem

LeetCode

Given two binary trees, 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:

  1. Input: 1 1
  2. / \ / \
  3. 2 3 2 3
  4. [1,2,3], [1,2,3]
  5. Output: true

Example 2:

  1. Input: 1 1
  2. / \
  3. 2 2
  4. [1,2], [1,null,2]
  5. Output: false

Example 3:

  1. Input: 1 1
  2. / \ / \
  3. 2 1 1 2
  4. [1,2,1], [1,1,2]
  5. Output: false

问题

力扣

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 1:

  1. 输入: 1 1
  2. / \ / \
  3. 2 3 2 3
  4. [1,2,3], [1,2,3]
  5. 输出: true

示例 2:

  1. 输入: 1 1
  2. / \
  3. 2 2
  4. [1,2], [1,null,2]
  5. 输出: false

示例 3:

  1. 输入: 1 1
  2. / \ / \
  3. 2 1 1 2
  4. [1,2,1], [1,1,2]
  5. 输出: false

思路

二叉树

Python3代码
  1. # Definition for a binary tree node.
  2. # class TreeNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution:
  8. def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
  9. # 两棵树都为空
  10. if not p and not q:
  11. return True
  12. # 一棵树为空,另一棵不为空
  13. elif not p or not q:
  14. return False
  15. # 两棵树都非空,但节点值不同
  16. elif p.val != q.val:
  17. return False
  18. # 分别判断左子树和右子树
  19. return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

GitHub链接

Python

发表评论

表情:
评论列表 (有 0 条评论,95人围观)

还没有评论,来说两句吧...

相关阅读

    相关 0100-Same Tree(相同)

    > 这个系列算是出于个人兴趣开的一个新坑吧,最近看到同学刷LeetCode算法题,就想写写那些可以一行Python代码写出来的题目,因此本专栏的文章的解题方式效率不做保证,只为