试编写一个函数,要在一棵树Tree中,找出最大值。函数原型如下: bool fnGetMax( struct TreeNode *Tree, int *max );

试编写一个函数,要在一棵树Tree中,找出最大值。函数原型如下:

bool fnGetMax( struct TreeNode *Tree, int *max );

假设二叉树采用左右孩子指针存储结构,即其结点数据类型描述为:
struct TreeNode{
int data;//数据域
struct TreeNode *left, *right;//指向其左右孩子结点
};
试编写一个函数,要在一棵树Tree中,找出最大值。函数原型如下:
bool fnGetMax( struct TreeNode *Tree, int *max );
//找到最大值则返回true,否则返回false;

设计算法并在主函数中调用:

#include <stdio.h>
#include <stdbool.h>
// 试编写一个函数,要在一棵树Tree中,找出最大值。
bool fnGetMax(struct TreeNode *Tree, int *max);
struct TreeNode
{
    
    
    int data;                      //数据域
    struct TreeNode *left, *right; //指向其左右孩子结点
};

int main()
{
    
    
    struct TreeNode root1; // init struct
    root1.data = 6;
    root1.left = root1.right = NULL; // 避免内存访问错误

    struct TreeNode root2; // init struct
    root2.data = 9;
    root2.left = root2.right = NULL;

    struct TreeNode root3; // init struct
    root3.data = 3;
    root3.left = root3.right = NULL;

    root1.left = &root2;
    root1.right = &root3;
    
    int max_num = root1.data;
    int *max = &max_num;
    fnGetMax(&root1,max);
    return 0;
}
bool fnGetMax(struct TreeNode *Tree, int *max) // 遍历二叉树
{
    
    
    if (Tree == NULL)
    {
    
    
        puts("find error!");
        return false;
    }
    if(Tree->left){
    
    
        fnGetMax(Tree->left,max);
    }
    if(Tree->right){
    
    
        fnGetMax(Tree->right,max);
    }
    if (*max < (Tree->data))
    {
    
    
        *max = Tree->data;
    }
    // puts("find success!");
    // printf("max = %d\n",*max);
    return true;
}

result:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44880154/article/details/110594749
今日推荐