两个递归+深度优先遍历 python3
树的子结构
http://www.nowcoder.com/questionTerminal/6e196c44c7004d15b1610b9afca8bd88
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here result = False if pRoot1 and pRoot2: if pRoot1.val == pRoot2.val: result = self.same(pRoot1,pRoot2) if not result: result = self.HasSubtree(pRoot1.left,pRoot2) if not result: result = self.HasSubtree(pRoot1.right,pRoot2) return result def same(self,p1,p2): if not p2: return True if not p1: return False return p1.val == p2.val and self.same(p1.left,p2.left)and self.same(p1.right,p2.right)