给定一棵二叉树的头结点head,任何两个节点之间都存在距离,返回整颗二叉树的最大距离(每个结点只经过一次)
class max{
public static int maxDistance(Node head){
return process(head).maxDistance;
}
public static class Info{
public int maxDistance;
public int height;
public Info(int dis,int h){
maxDistance = dis;
height = h;
}
}
public static Info process(Node X){
if(X == null){
return new Info(0,0);
}
Info leftInfo = process(X.left);
Info rightInfo = process(X.right);
int height = Math.max(leftInfo.height,rightInfo.height) + 1;
int maxDistance = Math.max(Math.max(leftInfo.maxDistance,rightInfo.maxDistance),
leftInfo.height + rightInfo.height + 1);
return new Info(maxDistance,height);
}
}
二叉树递归的套路
1.假设以X节点为头,假设可以向X左树和X右树要任何信息
2.在上一步的假设下,讨论以X为头结点的树,得到答案的可能性
3.列出所有可能性好,确定到底需要向左树和右树要什么样的信息
4.把左树信息和右树信息求全集,就是任何一颗子树都需要返回的信息S
5.递归函数都返回S,每一颗字树都这样要求
6.写代码,在代码中考虑如何把左树的信息和右树的信息整合出整颗树的信息。
本题最大距离有两种情况
1.和X节点无关,那么最大距离一定是左树的最大距离或者是右树的最大距离
2.和X节点有关,那么最大距离一定是左子树的高度 + 1 + 右子树的高度
本道题对左树和右树要的信息是一样的