解答
把一棵树序列化为字符串(字符数组) 如果str2是str1的子串 则T2也是T1的子树。
java参考代码如下:
package zuoshen1;
public class KMP_T1SubtreeEqualsT2 {
public static class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val){
this.val=val;
this.left=null;
this.right=null;
}
}
public static String preorder(TreeNode root){
StringBuilder sb=new StringBuilder();
precore(root,sb);
return sb.toString();
}
public static void precore(TreeNode root,StringBuilder sb){
if(root==null)
return;
sb.append(root.val);
sb.append("#");
if(root.left!=null){
precore(root.left,sb);
}
if(root.right!=null)
precore(root.right,sb);
}
public static boolean isSubtree(TreeNode root1,TreeNode root2){
String s1=preorder(root1);
String s2=preorder(root2);
return KMP.getIndexOf(s1,s2)!=-1?true:false;
}
public static void main(String[] args) {
TreeNode root=new TreeNode(1);
root.left=new TreeNode(2);
root.right=new TreeNode(3);
root.left.left=new TreeNode(4);
root.left.right=new TreeNode(5);
root.right.left=new TreeNode(6);
root.right.right=new TreeNode(7);
TreeNode other=new TreeNode(3);
other.left=new TreeNode(6);
other.right=new TreeNode(7);
System.out.println(preorder(root));
System.out.println(preorder(other));
System.out.println(isSubtree(root,other));
}
}
帖子还没人回复快来抢沙发