距离:将二叉树看着无环图,图的某一条路径的长度称为相应两点的距离
分析:
(1)如果这条路径通过根节点,这最大距离为 (h1-1)+(h2+1)+2=h1+h2 其中h1,h2分别为左右子树的高度;
(2)如果这条路径不通过根节点,则问题转换为左子树距离和右子树距离的最大值。
算法即使在上面两种情况中求最大值。算法采用递归的方式实现,递归过程中同时求子树的高度。
例子:
代码:
#include <iostream>
using namespace std;
struct BTreeNode
{
BTreeNode* pLeft;
BTreeNode* pRight;
BTreeNode() {
pLeft = pRight = NULL;
}
// value of tree node is not used in this program.
};
struct Pair
{
int dis;
int height;
Pair(int d, int h){
dis = d;
height = h;
}
};
int max(int a, int b) {
return a > b ? a:b;
}
Pair* disOfBT(BTreeNode* root) {
Pair* p1 = new Pair(0, 0), *p2 = new Pair(0, 0);
if(root->pLeft != NULL) {
p1 = disOfBT(root->pLeft);
}
if(root->pRight != NULL) {
p2 = disOfBT(root->pRight);
}
int height = max(p1->height, p2->height)+1;
int dis = max(max(p1->dis, p2->dis), p1->height+p2->height);
return new Pair(dis, height);
}
int main() {
// case 1:
BTreeNode* root = new BTreeNode;
root->pLeft = new BTreeNode;
root->pLeft->pLeft = new BTreeNode;
root->pLeft->pRight = new BTreeNode;
root->pLeft->pRight->pLeft = new BTreeNode;
root->pRight = new BTreeNode;
root->pRight->pLeft = new BTreeNode;
root->pRight->pRight = new BTreeNode;
root->pRight->pRight->pLeft = new BTreeNode;
cout << disOfBT(root)->dis << endl;
// case 2:
BTreeNode* root1 = new BTreeNode;
root1->pLeft = root;
root1->pRight = new BTreeNode;
cout << disOfBT(root1)->dis << endl;
return 0;
}
扩展:
上面的距离定义中每一条边的权重相等。如果权重没有限制的话,分析部分的第一种情况会发生变化。当最大距离的路径经过根节点时,过左右两边子树根节点的路径的最大长度不一定为高度。可以预先处理一遍整棵树,从叶节点开始,记录每个点到叶节点的最长(权重)路径。