您的位置:首页 > 其它

阿里2015年校园招聘笔试题

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

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

#include <stdio.h>
#include <malloc.h>

typedef struct node
{
int data;
struct node * lchild;
struct node * rchild;
}node;

node * Insert(node *t , int key)
{
if(t == NULL)
{
node * p;
p = (node *)malloc(sizeof(node));
p->data = key;
p->lchild = NULL;
p->rchild = NULL;
t = p;
}
else
{
if(key < t->data)
t->lchild = Insert(t->lchild, key);
else
t->rchild = Insert(t->rchild, key);
}
return t;
}

node * creat(node *t)
{
int i, n, key;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", &key);
t = Insert(t, key);
}
return t;
}

int getMinValue(node* t){
node* p = t;
while(p->lchild != NULL)
p = p->lchild;
return p->data;
}
int getMaxValue(node* t){
node* p = t;
while(p->rchild != NULL)
p = p->rchild;
return p->data;
}

int getBigestDifference(node* t){
return getMaxValue(t) - getMinValue(t);
}

int main()
{
node * t = NULL;
t = creat(t);
printf("the bigest difference %d\n", getBigestDifference(t));
return 0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: