JZ17-树的子结构
树的子结构
https://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
public class Solution { public boolean HasSubtree(TreeNode root1,TreeNode root2) { if(root1==null||root2==null){ return false; } //helper-HasSubtree-HasSubtree return helper(root1,root2)||HasSubtree(root1.left,root2)||HasSubtree(root1.right,root2); } private boolean helper(TreeNode root1,TreeNode root2){ if(root2==null){//B数完全消除 return true; } if(root1==null){//A树没有了,但B数还没完全消除。说明B中有A没有的结构 return false; } if(root1.val!=root2.val){ return false; }else{ return helper(root1.left,root2.left)&&helper(root1.right,root2.right); } } }