阿里笔试题

题目:写一个函数,输入一个二叉树,树中每个节点存放了一个整数值,函数返回这颗二叉树中相差最大的两个节点间的差值绝对值。请注意程序效率。

说明:根据题目的要求首先需要构造一个二叉树,首先想到的是构造一个二叉搜索树,这样找就可以很方便的寻找到最大值和最小值,从而求出差值最大的绝对值。

[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include <malloc.h>  
  3.   
  4. typedef struct node  
  5. {  
  6.     int data;  
  7.     struct node * lchild;  
  8.     struct node * rchild;  
  9. }node;  
  10.   
  11. node * Insert(node *t , int key)  
  12. {  
  13.     if(t == NULL)  
  14.     {  
  15.         node * p;  
  16.         p = (node *)malloc(sizeof(node));  
  17.         p->data = key;  
  18.         p->lchild = NULL;  
  19.         p->rchild = NULL;  
  20.         t = p;  
  21.     }  
  22.     else  
  23.     {  
  24.         if(key < t->data)  
  25.             t->lchild = Insert(t->lchild, key);  
  26.         else  
  27.             t->rchild = Insert(t->rchild, key);  
  28.     }  
  29.     return t;  
  30. }  
  31.   
  32. node * creat(node *t)  
  33. {  
  34.     int i, n, key;  
  35.     scanf("%d", &n);  
  36.     for(i = 0; i < n; i++)  
  37.     {  
  38.         scanf("%d", &key);  
  39.         t = Insert(t, key);  
  40.     }  
  41.     return t;  
  42. }  
  43.   
  44. int getMinValue(node* t){  
  45.     node* p = t;  
  46.     while(p->lchild != NULL)  
  47.         p = p->lchild;  
  48.     return p->data;  
  49. }  
  50. int getMaxValue(node* t){  
  51.     node* p = t;  
  52.     while(p->rchild != NULL)  
  53.         p = p->rchild;  
  54.     return p->data;  
  55. }  
  56.   
  57. int getBigestDifference(node* t){  
  58.     return getMaxValue(t) - getMinValue(t);  
  59. }  
  60.   
  61. int main()  
  62. {  
  63.     node * t = NULL;  
  64.     t = creat(t);  
  65.     printf("the bigest difference %d\n", getBigestDifference(t));  
  66.     return 0;  
  67. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值