发贴记录一下自己数据结构练习的代码~
代码实现功能:输出根节点到叶节点的最长的路径(输出节点值与路径长度)
关键代码:
//输出根节点到叶节点的最长的路径(输出节点值与路径长度)(deepth初始为1)
//path储存当前递归得到的路径,deepth储存当前递归得到的路径长,longestpath储存当前最长路径上每一个节点值,longestpath[0]储存当前最长路径长度
void PrintLongestRoad(TreeNode *tree, int path[], int &deepth,int longestpath[]) {
if (tree != NULL) {
//递归找到叶子节点,将叶子节点加入路径,将此路径与最大路径比较
if (tree->lchild == NULL && tree->rchild == NULL) {
path[deepth] = tree->value;
//如果出现了长度更长的路径,则更新当前最长路径
if (deepth > longestpath[0]) {
longestpath[0] = deepth;
for (int i = 1; i <= deepth; i++) {
longestpath[i] = path[i];
}
}
}
else {
path[deepth++] = 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[20];
int b[20];
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[0]; i++) {
cout << b[i] << "\t";
}
}
运行结果:
|