SHARE
TWEET

Untitled

a guest Apr 26th, 2019 56 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
  2.  
  3. * solution1: recursion
  4. ```python3
  5. # -*- coding:utf-8 -*-
  6. # class TreeNode:
  7. #     def __init__(self, x):
  8. #         self.val = x
  9. #         self.left = None
  10. #         self.right = None
  11. class Solution:
  12.     def HasSubtree(self, pRoot1, pRoot2):
  13.         # write code here
  14.         result = False
  15.         if pRoot1 and pRoot2:
  16.             if pRoo1.val == pRoot2.val:
  17.                 result = self.isSubtree(pRoot1,pRoot2)
  18.             if not result:
  19.                 result = self.HasSubtree(pRoot1.left,pRoot2)
  20.             if not result:
  21.                 result = self.HasSubtree(pRoot1.right,pRoot2)
  22.         return result
  23.        
  24.     def isSubtree(self,root1,root2):
  25.         if not root2:
  26.             return True
  27.         if not root1:
  28.             return False
  29.         if root1.val != root2.val:
  30.             return False
  31.         return self.isSubtree(root1.left,root2.left) and self.isSubtree(root1.right,root2.right)
  32. ```
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top