思路
- 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