1. 树的子结构
输入两棵二叉树A和B,判断B是不是A的子结构。
方法一:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSubStructure(A, B):
if not A or not B:
return False
return isSameTree(A, B) or isSubStructure(A.left, B) or isSubStructure(A.right, B)
def isSameTree(A, B):
if not B:
return True
if not A:
return False
if A.val!= B.val:
return False
return isSameTree(A.left, B.left) and isSameTree(A.right, B.right)
方法二:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSubStructure(A, B):
def dfs(node_A, node_B):
if not node_B:
return True
if not node_A or node_A.val!= node_B.val:
return False
return dfs(node_A.left, node_B.left) and dfs(node_A.right, node_B.right)
if not A or not B:
return False
stack_A = [A]
while stack_A:
node = stack_A.pop()
if node.val == B.val and dfs(node, B):
return True
if node.left:
stack_A.append(node.left)
if node.right:
stack_A.append(node.right)
return False
标签:node,right,return,val,Study,Part20,Algorithms,self,left
From: https://blog.csdn.net/qq_24058289/article/details/141792914