比如:
root1前序遍历结果为:sb1=1245367
root2前序遍历结果为:sb2=245
String[] strs =sb1.toString().split(sb2.toString());
strs的长度为2,表示含有子结构
特殊情况:遍历结果相等的话,strs为空
import java.lang.StringBuffer;
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
if(root2==null||root1==null) return false;//根据题目要求,都为null返回false
if(root1==root2) return true;//两个相等
StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = new StringBuffer();
preSort(root1,sb1);
preSort(root2,sb2);
String[] strs = sb1.toString().split(sb2.toString());
//根据strs的情况判断是否包含子树
if(strs.length>1||strs.equals("")) return true;//第一种情况表示可以分开,第二种表示二者相等
return false;
}
public static void preSort(TreeNode root,StringBuffer sb){
if(root==null) return;
//前序遍历
sb.append(root.val);
preSort(root.left,sb);
preSort(root.right,sb);
}
}


京公网安备 11010502036488号