一、要求
判断一棵树tree2是不是另一棵树tree1的子结构,空树不是任意一个树的子结构。
二、思路及代码
需要进行的判断:
1.都不是None,判断val,再进一步判断(左右进一步看val,或者左右重新判断)
2.tree1是空而tree2非空 ,return false
3.tree2已是空,return true
4.一开始就遇到空节点val==None:不论是tree1还是tree2 return false。
class TreeNode: def __init__(self,value=None): self.val=value self.left=None self.right=None def solution(tree1,tree2): if tree1 and tree2:#判断1:都不是None,判断val,再进一步判断(左右进一步看val,或者左右重新判断) if tree1.val==None or tree2.val==None:#判断4:遇到空节点,tree1 为空,tree2不可能是它的子树;tree2为空,空树不是任何树的子树 return False if tree1.val==tree2.val: return solution(tree1.left,tree2.left) and solution(tree1.right,tree2.right) else: return solution(tree1.left,tree2) or solution(tree1.right,tree2) if not tree1 and tree2:#判断2:tree1是空而tree2非空 ,return false return False return True #判断3:tree2已是空,return true def main(): #建立tree1 node1=TreeNode(1) node2=TreeNode(2) node3=TreeNode(3) node4=TreeNode(4) node5=TreeNode(5) node6=TreeNode(6) node1.left=node2 node1.right=node3 node3.right = node6 node2.left = node4 node2.right = node5 # 建立tree2 node7=TreeNode(2) node8=TreeNode(5) node7.right = node8 #建立tree3 node9=TreeNode(3) node10=TreeNode(7) node9.left=node10 #建立空树tree4 node11=TreeNode() print(solution(node1,node7)) print(solution(node1,node9)) print(solution(node1,node11)) if __name__=='__main__': main()
三、运行结果
TrueFalse
False
四、思考与总结
True False None都是大写开头