参考资料:
http://blog.youkuaiyun.com/lalor/article/details/7626678
http://blog.youkuaiyun.com/luckyxiaoqiang/article/details/7518888#comments
分为两种情况来讨论:
1)二叉树中最远的两个节点经过根节点,如情况A
2)二叉树中最远的两个节点不经过根节点,在其左子树或者右子树中
所以:二叉树中最远的距离 = 【(左子树距离根节点最远的节点 + 右子树距离根节点最远的节点),左子树中最远的距离,右子树中最远的距离】三者的最大值
#include <iostream>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <cstring>
/* maxleft 是指左子树中离根节点最远的距离,maxright指右子树离根节点最远的距离 */
int getmaxdistance(treeNode* root,int &maxleft,int &maxright){
if(root == NULL){
maxleft = 0;
maxright = 0;
return 0;
}
int maxLL,maxLR,maxRL,maxRR;
int leftmaxdis,rightmaxdis;
if(!root->left){
leftmaxdis = 0;
maxleft = 0;
}else{
leftmaxdis = getmaxdistance(root->left,maxLL,maxLR);
maxleft = max(maxLL,maxLR) + 1;
}
if(!root->right){
rightmaxdis = 0;
maxright = 0;
}else{
rightmaxdis = getmaxdistance(root->right,maxRL,maxRR);
maxright = max(maxRL,maxRR) + 1;
}
return max(max(leftmaxdis,rightmaxdis),maxleft+maxright);
}