题目:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思想:现根据在树A中查找与根节点的值一样的节点R。紧接着判断树A中以节点R为根节点的子树和树b是不是具有相同的结构。
java代码:
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public boolean HasSubtree(TreeNode root1,TreeNode root2) { boolean result=false; if(root1!=null && root2!=null) { if (root1.val == root2.val) { result = HasNextTree(root1, root2); } if (!result) { result = HasSubtree(root1.left, root2); } if (!result) { result = HasSubtree(root1.right, root2); } } return result; } public boolean HasNextTree(TreeNode root1,TreeNode root2){ if(root1==null&& root2!=null){ return false; } if(root2==null){ return true; } if(root1.val!=root2.val){ return false; } return HasNextTree(root1.left,root2.left) && HasNextTree(root1.right,root2.right); } }python代码:
class Solution: def HasSubtree(self, pRoot1, pRoot2): # write code here result = False if pRoot1 and pRoot2: if pRoot1.val == pRoot2.val: result = self.IsSubtree(pRoot1, pRoot2) if not result: result = self.HasSubtree(pRoot1.left, pRoot2) if not result: result = self.HasSubtree(pRoot1.right, pRoot2) return result def IsSubtree(self, pRoot1, pRoot2): if not pRoot2: return True if not pRoot1: return False if pRoot1.val != pRoot2.val: return False return self.IsSubtree(pRoot1.left, pRoot2.left) and self.IsSubtree(pRoot1.right, pRoot2.right)