【Leetcode】100—Same Tree
2019-07-14 本文已影响0人
Gaoyt__
一、题目描述
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例:
二、代码实现
对于树的操作,是必定要使用递归的方法的。对于求解书的任何问题,都先使用分治法,将树拆分为左子树和右子树(这里主要针对二叉树),如果左子树和右子树都符合条件,则这棵树满足条件。这里需要注意的是递归结束的条件以及递归过程。
# 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 == None and q == None: return True
elif p == None or q == None: return False
elif p.val == q.val:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
递归比较左子树、右子树是否相等。