LeetCode#100-Same Tree 解题思路

题目描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: 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)