请帮忙。您需要创建一棵二叉树并输出这棵树的最长路径。我确实向树中添加了元素并在屏幕上显示树,但我不知道如何继续。
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <stdio.h>
struct TNode
{
int info;
struct TNode* left, * right;
};
typedef struct TNode Node;
void push(Node** t, int a)
{
if (*t == NULL)
{
*t = (Node*)malloc(sizeof(Node));
(*t)->info = a;
(*t)->left = (*t)->right = NULL;
return;
}
if (a > (*t)->info) push(&((*t)->right), a);
else push(&((*t)->left), a);
}
void showTree(Node* t)
{
if (t == NULL) return;
showTree(t->left);
printf("%i ", t->info);
showTree(t->right);
}
int main()
{
Node* tree = NULL;
int n;
int s;
printf("Enter number of items ");
scanf("%i", &n);
for (int i = 0; i < n; ++i)
{
printf("Enter information ");
scanf("%i", &s);
push(&tree, s);
}
printf("Tree\n");
showTree(tree);
return 0;
}
像你的 showtree 一样进行遍历,并将节点的深度传递给下一层递归。
记住某处的最大深度,当你再次遍历时,找到深度最大的那个节点,然后返回根,一路输出所有内容