python - Python 3 出现此代码错误(另一棵树的子树)
问题描述
当我运行此代码时,它应该给我 false,但它只返回 true 特别针对此 inputL [3,4,5,1,2,null,null,0] [4,1,2]
概念是:给定两个非空二叉树 s 和 t,检查树 t 是否与 s 的子树具有完全相同的结构和节点值。s 的子树是由 s 中的一个节点和该节点的所有后代组成的树。树 s 也可以被认为是它自己的子树。
class Solution:
src = []
def traverseToVal(self, s, v):
if not s:
return
if s.val == v:
self.src.append(s)
return
self.traverseToVal(s.left, v)
self.traverseToVal(s.right, v)
def isSame(self, s, t):
if not s and not t:
return True
if s and not t:
return False
if t and not s:
return False
return s.val == t.val and self.isSame(s.left, t.left) and self.isSame(s.right, t.right)
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
if not s and not t:
return True
if s and not t:
return False
if t and not s:
return False
# stands for "subtree root candidate"
self.traverseToVal(s, t.val)
if not self.src:
return False
# print(self.src)
out = []
for src in self.src:
out.append(self.isSame(src, t))
return any(out)
解决方案
推荐阅读
- python - VerificationSMSCode() 得到了一个意外的关键字参数“电话”
- python - Pytest:捕获的标准错误设置和捕获的日志设置重复
- c# - 如何检查 `SomeType<>` 是否实现了 `SomeInterface<>`?
- python - 将 numpy 时间戳数组格式化为连接字符串
- java - Java android在右下角的照片中添加时间戳
- javascript - React Query v3 useInfiniteQuery 返回 isLoading,isFetching 始终为 true,isFetchingNextPage 始终为 false
- c++ - 如何创建矢量
? - python-3.x - 如何让 Django 接受我的日期格式
- sql - 带有 IF 条件的 Postgres 触发器
- react-native - React Navigation 自定义标题和自定义返回按钮