给定一棵二叉树,求出树中两个结点距离的最大值。
首先明确距离最大的两个结点出现位置:1,同时在根结点的左子树中;2,同时在根结点的右子树中;3,左右子树中各有一个结点。
假设我们分别得到了根结点左子树中两个结点最长距离,右子树中两个结点最长距离(这是求整棵树中两个结点最长距离的子问题罢了,既然程序能够求出整棵树两个结点最长距离,那么求左右子树中的最长距离只不过是两次递归调用而已),还要得到根结点左子树高度(最低层为0),这个高度代表左子树中最底层结点到根结点距离(图四),同样可以得到右子树高度。
将左子树两个结点最长距离,有结点两个结点最长距离,左、右子树高度之和比较,取得三者中的最大值,即为这棵二叉树中两个结点距离的最大值。
代码如下:
typedef struct Node {
struct Node *lchild;
struct Node *rchild;
//左右子树高度(最底层结点到当前结点距离)及左右子树最大高度
int lHeight, rHeight, height;
}
int findMaxLen(Node *root) {
int lMaxLen, rMaxLen;
if(root == NULL) return 0;
lMaxLen = findMaxLen(root->lchild);
rMaxLen = findMaxLen(root->rchild);
if(root->lchild == NULL) root->lHeight = 0;
else root->lHeight = (root->lchild->height) + 1;
if(root->rchild == NULL) root->rHeight = 0;
else root->rHeight = (root->rchild->height) + 1;
//以当前结点为根结点的树的最大高度(长度)
root->height = root->lHeight > root->rHeight ? root->lHeight : root->rHeight;
return max(lMaxLen, rMaxLen, root->lHeight + root->rHeight); //max求三者最大值
}
class LongestDistance {
public:
int findLongest(TreeNode* root) {
assert(root != NULL);
int res = 0;
int mt[501];
find_longest_detail(root, mt, res);
return res;
}
private:
void find_longest_detail(TreeNode* t, int *mt, int& res){
int lmax = 0, rmax = 0;
if(t->left != NULL){
find_longest_detail(t->left, mt, res);
lmax = mt[t->left->val];
}
if(t->right != NULL){
find_longest_detail(t->right, mt, res);
rmax = mt[t->right->val];
}
mt[t->val] = std::max(lmax, rmax) + 1;
res = lmax + rmax + 1 > res ? lmax + rmax + 1 : res;
}
};