public class trees<T> {
private T data;
public trees<T> left;
public trees<T> right;
public trees(T data) {
this.data = data;
this.left = null;
this.right = null;
}
public trees(T data, trees<T> left, trees<T> right) {
this.data = data;
this.left = left;
this.right = right;
}
public int maxDepth(trees<T> t)//树的最大深度,后序递归
{
if(t==null)
{
return 0;
}
int d1=maxDepth(t.left);
int d2=maxDepth(t.right);
return Integer.max(d1,d2)+1;
}
public boolean duichen(trees<T> t)//对称树判断
{
return check(t.left,t.right);
}
public boolean check(trees<T> left,trees<T> right)
{
if(left==null&&right==null)
{
return true;
}
if(left==null||right==null)
{
return false;
}
if(left.data!=right.data)
{
return false;
}
return check(left.left,right.right)&&check(left.right,right.left);
}
}
public class Main {
public static void main(String[] args) {
trees<Integer> t=new trees<>(1);
trees<Integer> t1=new trees<>(2);
trees<Integer> t2=new trees<>(3);
trees<Integer> t3=new trees<>(4);
trees<Integer> t4=new trees<>(5);
t.left=t1;
t.right=t2;
t1.left=t3;
t1.right=t4;
System.out.println("最大深度");
System.out.println(t.maxDepth(t));
System.out.println(t.duichen(t));
trees<Integer> s=new trees<>(1);
trees<Integer> s1=new trees<>(2);
trees<Integer> s2=new trees<>(2);
s.left=s1;
s.right=s2;
System.out.println(t.duichen(s));
}
}