【leetcode】-100. Same Tree判断相同树

本文介绍如何解决LeetCode上的100题,即判断两个二叉树是否结构相同且节点值相等。通过递归方法,首先比较根节点,再递归检查左右子树,若节点值和结构均一致则为相同二叉树。
摘要由CSDN通过智能技术生成

题目

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:

Input:

	   1         1
      / \       / \
     2   3     2   3

    [1,2,3],   [1,2,3]

Output: true

Example 2:

Input:

	   1         1
      /           \
     2             2

    [1,2],     [1,null,2]

Output: false

Example 3:

Input:

	   1         1
      / \       / \
     2   1     1   2

    [1,2,1],   [1,1,2]

Output: false

递归

对二叉树的操作一般可以用递归来处理。
判断两个二叉树是否相等,首先看要比较的两个节点是否相等,然后递归遍历其左右子树。

判断两个节点相等:1、如果两节点都为空,那么相等;2、如果一个为空一个不为空,则不相等;3、如果两个节点值不等,则不相等。

python 代码

# 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: TreeNode, q: 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
        return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值