
LeetCode 100. Same Tree.jpg
LeetCode 100. Same Tree
Description
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
描述
- 此題目是給定兩棵樹,判斷兩個(gè)樹是否相等.
- 兩顆樹相等意味著結(jié)構(gòu),值要完全一樣.
- 此題目使用遞歸求解.
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2018-12-28 19:06:08
# @Last Modified by: 何睿
# @Last Modified time: 2018-12-28 19:12:16
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
# 如果第一個(gè)樹和第二個(gè)樹都是空,說明兩個(gè)樹是相等的,返回True.
if not p and not q:
return True
# 如果有一個(gè)數(shù)為空另一個(gè)樹不為空,說明兩個(gè)樹一定不會相等
if not p or not q:
return False
# 如果兩個(gè)樹的節(jié)點(diǎn)值不相等,則兩條樹不會相等,返回False
if p.val != q.val:
return False
# 如果以上條件都通過了,說明兩個(gè)樹的當(dāng)前節(jié)點(diǎn)相等
# 我們分別判斷這兩條樹的左子樹是否相等,右子樹是否相等
left = self.isSameTree(p.left,q.left)
right = self.isSameTree(p.right,q.right)
# 返回最終結(jié)果
return left and right
源代碼文件在這里.
?本文首發(fā)于何睿的博客,歡迎轉(zhuǎn)載,轉(zhuǎn)載需保留文章來源,作者信息和本聲明.