第100题:
题目:"
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.
"
简单解释:就是给出两棵树,判断他们是否是相同的
算法思想:本题是属于简单题,算法的关键是明确相同到底是什么含义,由于树是递归来定义的,那么就是根节点相同,并且左右子树都相同,那么这两棵树就是相同的。
PS:作者在刚开始实现的时候,老是分不清not 和None的区别,导致自己走了一个大弯,给自己一个提醒:
https://blog.csdn.net/Sasoritattoo/article/details/12451359
好了,直接给出注释的代码吧,是基于python 3的:
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def learn_isSameTree(self,p:TreeNode,q:TreeNode):
if not p and not q: # p,q均为空的时候,相同
return True
if not p or not q:
return False
if p.val == q.val: #若p和q的值相同,那么递归判断它们的左右子树是否相同
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
return False
第101题:
题目:"
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
"
题目解释:就是给出一颗树,判断它是不是关于自身对称的
算法思想:第一次在思考的时候,一个简单的想法就是基于树的遍历思想,只不过在遍历的时候遍历的方向要相反才能判断,并且 单独写了两个遍历函数,感觉麻烦了,代码就不贴出来了,思想到代码即可写出。
大牛的解法(个人理解):采用类似于层次遍历的方法,借助于栈,然后进行判断,详细的注释见代码:
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
"""
利用栈来进行判断,分别进行判断
:param root:
:return:
"""
# 树为空
if not root:
return True
# 将树的左右孩子结点入栈
stack=[(root.left,root.right)]
while stack:
# 取出左右孩子结点,并进行是否相等的判断
nodes=stack.pop()
l,r=nodes
if l is None and r is None:
continue
if l is None or r is None:
return False
if l.val != r.val:
return False
# 按照对称的性质,将相对应的结点加入栈中
stack.append((l.right, r.left))
stack.append((l.left, r.right))
return True
结语
一直在学习的路中...