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
思路
这道题很简单我们使用前序遍历的方法一个一个的进行比较,然后判断是否相等,如果中途任意一个不相等或者一个节点为空都直接返回false。
解题代码
1 # Definition for a binary tree node.
2 # class TreeNode(object):
3 # def __init__(self, x):
4 # self.val = x
5 # self.left = None
6 # self.right = None
7
8 class Solution(object):
9 def isSameTree(self, p, q):
10 """
11 :type p: TreeNode
12 :type q: TreeNode
13 :rtype: bool
14 """
15 if not p and not q:
16 return True
17 if not p or not q:
18 return False
19 if p.val == q.val:
20 return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
21 return False
一开始写的解决代码,但是发现可以写的更简单一点
1 # Definition for a binary tree node.
2 # class TreeNode(object):
3 # def __init__(self, x):
4 # self.val = x
5 # self.left = None
6 # self.right = None
7
8 class Solution(object):
9 def isSameTree(self, p, q):
10 """
11 :type p: TreeNode
12 :type q: TreeNode
13 :rtype: bool
14 """
15 if not p and not q:
16 return True
17 return self.preorder(p, q)
18
19
20 def preorder(self, p, q):
21 if not p and not q: # 都为空返回True
22 return True
23 if not p or not q: # 如果其中一个为空返回False
24 return False
25 if p.val == q.val: # 值相等的话直接继续判断
26 res = self.preorder(p.left, q.left) and self.preorder(p.right, q.right)
27 return res
28 return False