Leetcode 100. Same Tree

该博客讨论了如何通过递归算法判断两棵二叉树是否结构相同。当两棵树的所有子树在结构上完全一致且节点值相等时,它们被认为是相同的。给出的Python代码实现了一个`isSameTree`函数,首先检查根节点是否存在,然后比较节点值和左、右子树的结构。如果所有条件都满足,则返回True,否则返回False。

Problem

Given the roots of two binary trees p and q, 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.

Algorithm

Recursion. If two trees are structurally identical for all the sub-trees, the node values are same and the left, right sub-tree are all structurally identical.

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q :
            return True
        print(p, q)
        if (p and not q) or (not p and q) or (p.val != q.val) :
            return False
        
        if not self.isSameTree(p.left, q.left) :
            return False
        
        if not self.isSameTree(p.right, q.right) :
            return False
        
        return True
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值