输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
递归python版:
# -*- 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 if pRoot1 is None or pRoot2 is None: return False cur1 = pRoot1 cur2 = pRoot2 res = False if cur1.val == cur2.val: res = self.istree1hastree2(cur1,cur2) if not res: res = self.HasSubtree(cur1.left, cur2) if not res: res = self.HasSubtree(cur1.right, cur2) return res def istree1hastree2(self, tree1, tree2): if tree2 is None: return True if tree1 is None: return False res1 = False res2 = False if tree1.val == tree2.val: res1 = self.istree1hastree2(tree1.left,tree2.left) res2 = self.istree1hastree2(tree1.right,tree2.right) return (res1 and res2)