输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 class Solution: 8 def isSubWithRoot(self,pRoot1,pRoot2): 9 if pRoot2 == None: 10 return True 11 if pRoot1 == None: 12 return False 13 if pRoot1.val != pRoot2.val: 14 return False 15 return self.isSubWithRoot(pRoot1.left,pRoot2.left) and self.isSubWithRoot(pRoot1.right,pRoot2.right) 16 17 def HasSubtree(self, pRoot1, pRoot2): 18 if pRoot1 == None or pRoot2 == None: 19 return False 20 return self.isSubWithRoot(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2) 21 # write code here
Java版本,leetcode地址:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public boolean isSubStructure(TreeNode A, TreeNode B) { 12 if(A == null || B == null){ 13 return false; 14 } 15 return isSubTree(A,B) || isSubStructure(A.left,B) || isSubStructure(A.right,B); 16 } 17 18 public boolean isSubTree(TreeNode A,TreeNode B){ 19 if(B == null){ 20 return true; 21 } 22 if(A == null){ 23 return false; 24 } 25 if(A.val != B.val){ 26 return false; 27 } 28 return isSubTree(A.left,B.left) && isSubTree(A.right,B.right); 29 } 30 }