剑指 Offer 26. 树的子结构
思路
- dfs
注意注释掉的代表完全子树
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def helper(a, b):
# if not a and not b:
# return True
# if not a and b:
# return False
# if a and not b:
# return False
if not b:
return True
if not a:
return False
if a.val == b.val:
return helper(a.left, b.left) and helper(a.right, b.right)
else:
return False
if not B or not A:
return False
return helper(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
- 迭代
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return
stack = [root]
while stack:
cur = stack.pop()
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
cur.left, cur.right = cur.right, cur.left
return root
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步