这段时间屁事儿实在是有些多
弄得自己实在是没有心情来刷题了
本来今天也不想刷题的
哈哈哈哈哈哈哈哈哈哈哈
但是想到还是要克服惰性
所以就硬着头皮上了
果然,一段时间没碰题目
就有些手生了!!!
100-相同的树
给定两个二叉树,编写一个函数来检验它们是否相同。
如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。
示例 1:
输入: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
输出: true
示例 2:
输入: 1 1
/ \
2 2
[1,2], [1,null,2]
输出: false
示例 3:
输入: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
输出: false
思路:
这一题是比较简单的,树有三种遍历方式,即先序、中序、后序遍历,只需选取一种遍历方式同时对这两棵树遍历即可。只要有一个节点上的值不相等,说明这两棵树不相等,反之则相等。另外,虽然题目不要求我们构建树,但是为了自己测试的时候更容易看到其内部结果,所以我们还是要写出createTree()函数,具体函数参考我之前写的一篇文章:
https://blog.csdn.net/weixin_36431280/article/details/88901634
代码如下:
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 is not None and q is not None:
if p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right):
return True
else:
return False
elif p is None and q is None:
return True
else:
return False
def createBTree(self, data, index=0):
pNode = None
if index < len(data):
pNode = TreeNode(data[index])
pNode.left = self.createBTree(data, 2*index+1)
pNode.right = self.createBTree(data, 2*index+2)
return pNode
if __name__ == "__main__":
p_list = [1, 2]
q_list = [1, None, 2]
p_node = Solution().createBTree(p_list)
q_node = Solution().createBTree(q_list)
is_same = Solution().isSameTree(p_node, q_node)
print(is_same)
执行效率属于中等!