基本模仿CC150上的思路,递归地在t1中寻找能与t2的根相同的节点,作为开始比较的开始点,然后递归的比较两个树是否相等。
boolean containsTree(TreeNode t1, TreeNode t2){ if(t2==null) return true; return subTree(t1,t2); } boolean subTree(TreeNode t1, TreeNode t2){ if(t1==null) return false; if(t1.val ==t2.val){ if(matchTree(t1,t2)) return true; } return subTree(t1.left,t2)||subTree(t1.right,t2); } boolean matchTree(TreeNode t1, TreeNode t2){ if(t1==null&&t2==null) return true; if(t1==null||t2==null) return false; if(t1.val!=t2.val) return false; return matchTree(t1.left,t2.left)&&matchTree(t1.right,t2.right); }
时间: 2024-11-04 02:28:11