题目:给定一棵二叉树的头节点head,请返回最大搜索二叉子树的大小
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data)
{
this.value=data;
}
}
public static class ReturnType{
public int size;
public Node head;
public int min;
public int max;
public ReturnType(int a,Node b,int c,int d)
{
this.size=a;
this.head=b;
this.min=c;
this.max=d;
}
}
public static ReturnType process(Node head)
{
if(head==null) {
return new ReturnType(0,null,Integer.MAX_VALUE,Integer.MIN_VALUE);
}
Node left=head.left;
ReturnType leftSubTressInfo=process(left);
Node right=head.right;
ReturnType rightSubTressInfo=process(right);
int includeItself=0;
if(leftSubTressInfo.head==left&&
rightSubTressInfo.head==right&&
head.value>leftSubTressInfo.max&&
head.value<rightSubTressInfo.min)
{
includeItself=leftSubTressInfo.size+1+rightSubTressInfo.size;
}
int p1=leftSubTressInfo.size;
int p2=rightSubTressInfo.size;
int maxSize=Math.max(Math.max(p1, p2), includeItself);
Node maxHead=p1 > p2?leftSubTressInfo.head:rightSubTressInfo.head;
if(maxSize==includeItself) {
maxHead=head;
}
return new ReturnType(maxSize, maxHead,
Math.min(Math.min(leftSubTressInfo.min, rightSubTressInfo.min), head.value),
Math.max(Math.max(leftSubTressInfo.max, rightSubTressInfo.max), head.value));
}
public class Node{
public int huo;
public List<Node>nexts;
public Node(int huo)
{
this.huo=huo;
}
}
public static int getMaxhuo(Node head)
{
ReturnData data=process(head);
return Math.max(data.bulai_huo, data.lai_huo);
}
public class ReturnData{
public int lai_huo;
public int bulai_huo;
public ReturnData(int lai_huo,int bulai_huo)
{
this.lai_huo=lai_huo;
this.bulai_huo=bulai_huo;
}
}
public static ReturnData process(Node head)
{
int lai_huo=head.huo;
int bulai_huo=0;
for(int i=0;i<head.nexts.size();++i)
{
Node next=head.nexts.get(i);
ReturnData returndata=process(next);
lai_huo+=returndata.bulai_huo;
bulai_huo+=Math.max(returndata.lai_huo,returndata.bulai_huo);
}
return new ReturnData(lai_huo,bulai_huo);
}
3判断一个棵树是不是平衡二叉树
和上面类似:
我们从底层的节点开始比较,看每个节点符不符合平衡二叉树的概念,如果有一个不符合就不是平衡二叉树。所以每个节点要返回它是不是平衡二叉树,还要返回一个level,这个level的作用在于判断一个节点是不是平衡二叉树的根节点,根据Math.abs(左树高度-右树高度)>1判断它不是平衡二叉树,其余情况就是。
public static class Node
{
public int value;
public Node left;
public Node right;
public Node(int data)
{
this.value=data;
}
}
public static class ReturnType{
public int level;
public boolean isB;
public ReturnType(int level,boolean isB)
{
this.level=level;
this.isB=isB;
}
}
public static ReturnType process(Node head)
{
if(head==null)
{
return new ReturnType(0,true);
}
ReturnType leftSubTreeInfo=process(head.left);
if(!leftSubTreeInfo.isB)
{
return new ReturnType(0,false);
}
ReturnType rightSubTreeInfo=process(head.right);
if(!rightSubTreeInfo.isB)
{
return new ReturnType(0, false);
}
if(Math.abs(rightSubTreeInfo.level-leftSubTreeInfo.level)>1)
{
return new ReturnType(0,false);
}
return new ReturnType(Math.max(leftSubTreeInfo.level, rightSubTreeInfo.level),true);
}