没有优化,写的很烂!给大家分享一下,优化的地方有很多的哈哈。。。。
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<TreeNode> array = new ArrayList<TreeNode>();
ArrayList<Boolean> array2 = new ArrayList<Boolean>();
ArrayList<TreeNode> array3 = new ArrayList<TreeNode>();
ArrayList<TreeNode> array4= new ArrayList<TreeNode>();
Integer a = 0;
Integer b = 0;
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
if(root1==null || root2==null ){
return false;
}
isSame(root1,root2);
treeMax(root2);
System.out.print(a);
System.out.print(b);
for(int i = 0; i < array.size();i++){
booleanSame(array.get(i),root2);
if(array2.size() == array3.size()-1 && array3.size()-1>0){
if(b<a) return false;
return true;
}
array2 = new ArrayList<Boolean>();
array3 = new ArrayList<TreeNode>();
}
return false;
}
public void isSame(TreeNode root1,TreeNode root2){
if(root1==null) return ;
if(root1.val == root2.val){
array.add(root1);
}
b++;
isSame(root1.left,root2);
isSame(root1.right,root2);
}
public void treeMax(TreeNode root){
if(root==null) return ;
a++;
treeMax(root.left);
treeMax(root.right);
}
public void booleanSame(TreeNode root1,TreeNode root2){
if(root2== null){
array3.add(root2);
return ;
}
if(root1== null ){
return ;
}
if(root1.val == root2.val){
array2.add(true);
}
booleanSame(root1.left,root2.left);
booleanSame(root1.right,root2.right);
}
}

京公网安备 11010502036488号