阿里2014笔试题及答案


该题是阿里2014年校园招聘的一道笔试题,我自己写了一下,代码如下:

#include<iostream>
#include<cmath>
#include <conio.h>
#include<vector>

using namespace std;

static int value = 0;
static int Vmax ;
static int Vmin ;

struct tree
{
	int data;
	tree *left,*right;
};

class Btree
{
    static int n;
    static int m;
public:
    tree *root;
    Btree()
    {
        root=NULL;
    }
    void create_Btree(int);
    void Preorder(tree *);                  //先序遍历
    void display1() 
	{
		Preorder(root); 
		cout<<endl;
	} 
}; 

int Btree::n=0;
int Btree::m=0;

void Btree::create_Btree(int x)
{
    tree *newnode=new tree;
    newnode->data=x;
    newnode->right=newnode->left=NULL;
    if(root==NULL)
        root=newnode;
    else
    {
        tree *back;
        tree *current=root;
        while(current!=NULL)
        {
            back=current;
            if(current->data>x)
                current=current->left;
            else
                current=current->right;
        }
        if(back->data>x)
            back->left=newnode;
        else
            back->right=newnode;
    }
}

void Btree::Preorder(tree *temp)    //这是先序遍历二叉树,采用了递归的方法。
{
	int temp_value = 0;
    if(temp!=NULL)
    {
		if(temp->data>Vmax)
		{
			Vmax = temp->data;
		}
		else if(temp->data<Vmin)
		{
			Vmin = temp->data;
		}
	temp_value = abs(Vmax-Vmin);
	if(temp_value>value)
	{
		value = temp_value;
	}
    cout<<temp->data<<endl;
    Preorder(temp->left);
    Preorder(temp->right);
    }
}

int main()
{

	vector<int> vec;
	Btree A;
	int a;
	while(cin>>a)
	{
		//要先push_back(a)再判断,否则最后一个跟回车混在一起,没有push进去
		vec.push_back(a);
		if(getchar()==10)
		{
			break;
		}
	}
	int k = vec.size();
	for(int i = 0;i<vec.size();i++)
	{
		A.create_Btree(vec[i]);
	}
		cout<<endl;
	Vmax = vec[0];
	Vmin = vec[1];
    cout<<endl<<"先序遍历序列"<<endl;
	A.display1();
	cout<<"节点间最大值为:\n";
	cout<<value<<endl;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值