1、描述
如题:每个节点有一个权值,找到最大权值节点,到最小权值节点的距离,一个算1个
2、关键字
求距离,最大,最小节点
3、思路
首先遍历所有,求出最大和最小的节点,
然后寻找最近的公共父节点,
然后从父节点两个节点的值,相加
6、code
class Tree {
public:
int minleaf = 100000;
int maxleaf = 0;
void getmaxmin(TreeNode * root) { // 获取最小,最大权值的节点Node,
if (!root) return;
if (!root->left && !root->right) {
if (root->val < minleaf)
minleaf = root->val;
if (root->val > maxleaf)
maxleaf = root->val;
}
getmaxmin(root->left);
getmaxmin(root->right);
}
TreeNode * getcommon(TreeNode * root) { / 获取公共父节点
if (!root) return nullptr;
if (root->val == minleaf || root->val == maxleaf) {
return root;
}
auto pL = getcommon(root->left);
auto pR = getcommon(root->right);
if (!pL) return pR;
else if (!pR) return pL;
else return root;
}
int getdist(TreeNode* src, TreeNode * des) {
if (!src) return -1;
if (src->val == des->val) return 0;
int dist = getdist(src->left, des);
if (dist == -1)
dist = getdist(src->right, des);
if (dist != -1)
return dist + 1;
return -1;
}
int getDis(TreeNode* root) {
getmaxmin(root);
auto min = new TreeNode(minleaf);
auto max = new TreeNode(maxleaf);
auto com = getcommon(root);
int minpath = getdist(com, min);
int maxpath = getdist(com, max);
return minpath + maxpath;
}
};