【c++】【笔记】数据结构算法的练习 <输出根节点到叶节点的最长的路径>
发贴记录一下自己数据结构练习的代码~代码实现功能:输出根节点到叶节点的最长的路径(输出节点值与路径长度)
关键代码:
```
//输出根节点到叶节点的最长的路径(输出节点值与路径长度)(deepth初始为1)
//path储存当前递归得到的路径,deepth储存当前递归得到的路径长,longestpath储存当前最长路径上每一个节点值,longestpath储存当前最长路径长度
void PrintLongestRoad(TreeNode *tree, int path[], int &deepth,int longestpath[]) {
if (tree != NULL) {
//递归找到叶子节点,将叶子节点加入路径,将此路径与最大路径比较
if (tree->lchild == NULL && tree->rchild == NULL) {
path = tree->value;
//如果出现了长度更长的路径,则更新当前最长路径
if (deepth > longestpath) {
longestpath = deepth;
for (int i = 1; i <= deepth; i++) {
longestpath = path;
}
}
}
else {
path = tree->value;
PrintLongestRoad(tree->lchild, path, deepth, longestpath);
PrintLongestRoad(tree->rchild, path, deepth, longestpath);
deepth--;//从当前层出发所找到的叶子节点的路径比较完毕,返回上一层,再从上一层出发寻找叶子节点
}
}
}``
```
数据测试:
```
int main(){
BinaryTree *tree = creatBinaryTree();
int num = 1;
int a;
int b;
insertNode(tree, 1);
insertNode(tree, 32);
insertNode(tree, 0);
insertNode(tree, 3);
insertNode(tree, 20);
insertNode(tree, 40);
insertNode(tree, 2);
//insertNode(tree, 4);
insertNode(tree, 10);
insertNode(tree, 25);
insertNode(tree, 35);
insertNode(tree, 23);
PrintLongestRoad(tree->root, a, num, b);
for (int i = 1; i <= b; i++) {
cout << b << "\t";
}
}
```
运行结果:
收藏学习 下载学习 下载学习了 好好学习!!!!!!!!!!!! 学习一下思路。谢谢
页:
[1]