题目描述:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
题目大意:
给定两棵二叉树,编写函数检查它们是否相等。
当且仅当两棵二叉树的结构相同并且节点值也相同时,判定为相等。
解题思路:
递归(Recursion)
Python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if p and q:
return p.val == q.val and \
self.isSameTree(p.left, q.left) and \
self.isSameTree(p.right, q.right)
return p is None and q is None
本文链接:https://bookshadow.com/weblog/2016/08/18/leetcode-same-tree/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。
如果这篇博客对你有帮助,请支持书影博客
你的捐赠将用于服务器与域名费用,帮助免费技术内容持续更新。
支付宝
微信
建议金额:¥5 / ¥10 / ¥20 / ¥50(扫码后自行输入)