如果有人需要,我会留下这个答案。这是我在 C++ 中的解决方案。该函数Get_Max_Path()
返回一个具有最长路径的向量,因此您可以得到路径、长度和总和(如果需要):
vector<int> Max_Path(vector<int>rightpath, vector<int>leftpath)
{
return (rightpath.size() > leftpath.size()) ? rightpath : leftpath;
}
vector<int> GetPath(node* N, vector<int> v)
{
v.push_back(N->Data);
return v;
}
vector<int> Get_Max_Path(node* root)
{
if (!root) return
vector<int>(0);
return Max_Path(GetPath( root, Get_Max_Path(root->Right)),
GetPath( root, Get_Max_Path(root->Left)) );
}
这是树形结构
class node
{
public:
node* Right = NULL;
node* Left = NULL;
int Data;
};
class Tree
{
private:
node* Root = NULL;
public:
void Insert_Node(int Data)
{
node* DataNode = (node*)malloc(sizeof(node));
DataNode->Data = Data;
DataNode->Left = DataNode->Right = NULL;
if (Root == NULL) {
Root = DataNode;
return;
}
node* tmp_root = Root, * prev = NULL;
while (tmp_root != NULL)
{
prev = tmp_root;
tmp_root = (tmp_root->Data < Data) ?
tmp_root->Right :
tmp_root->Left;
}
(prev->Data < Data) ? (prev->Right = DataNode) : (prev->Left = DataNode);
}
vector<int> Max_Path(vector<int>rightpath, vector<int>leftpath)
{
return (rightpath.size() > leftpath.size()) ? rightpath : leftpath;
}
vector<int> Update_Path(node* N, vector<int> v)
{
v.push_back(N->Data);
return v;
}
vector<int> Get_Max_length_Path(node* root)
{
if (!root) return
vector<int>(0);
return Max_Path(
Update_Path(root, Get_Max_length_Path(root->Right)),
Update_Path(root, Get_Max_length_Path(root->Left)));
}
vector<int> Get_Max_length_Path()
{
return Get_Max_length_Path(Root);
}
};
这是驱动代码
int main()
{
Tree T;
int nodes[] = { 11, 6, 8, 19, 4, 13, 5, 17, 43, 49, 16, 31, 32};
int length = sizeof(nodes) / sizeof(nodes[0]);
for (size_t i = 0; i < length; i++)
T.Insert_Node(nodes[i]);
int sum = 0;
vector<int> path = T.Get_Max_length_Path();
cout << "The path length is : " << path.size() <<endl;
cout << "The path from the leaf to the root is : ";
for (int i = 0; i < path.size(); i++)
{
cout << path[i] << " ";
sum += path[i] ;
}
cout << endl;
cout << "the path sum is :" << sum << endl;
return 0;
}
测试用例
BST 样本
输出
The path length is : 5 The path from the leaf to the root is : 16 17
13 19 11 the path sum is :76