IGT 2014年校园招聘笔试题

时间:2022-11-30 18:51:08

2014年9月26日

华科

1. 

#include <iostream>
using namespace std;

int main()
{
int i = 4;
double d = 5.0;

cout<<sizeof(i < d ? i : d)<<endl;

system("pause");
return 0;
}

由于在i和d比较的时候,i会转换成double类型,所以输出为8.

2.

#include <iostream>
using namespace std;

class Base
{
public:
virtual void output(int i=4)
{
cout<<"Base::output "<<i<<endl;
}
};

class Derived : public Base
{
public:
void output(int i=5)
{
cout<<"Derived::output "<<i<<endl;
}
};

int main()
{
Base *p;
Derived d;
p = &d;
p->output();

system("pause");
return 0;
}

当通过基类指针(该基类指针指向派生类对象)调用虚函数的时候,且虚函数有默认参数值的时候,调用派生类的函数,如果不指定参数值,使用默认参数值的话,参数值使用基类的默认参数值。

3. 层次遍历二叉树

#include <iostream>
#include <deque>
using namespace std;

struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode *m_pLeft;
BinaryTreeNode *m_pRight;
};

void PrintByLevel(BinaryTreeNode *pRoot)
{
if (NULL == pRoot)
{
return ;
}

deque<BinaryTreeNode *> dq;

dq.push_back(pRoot);

while (dq.size() > 0)
{
BinaryTreeNode *pNode = dq.front();
dq.pop_front();

cout<<pNode->m_nValue<<endl;

if (pNode->m_pLeft != NULL)
{
dq.push_back(pNode->m_pLeft);
}

if (pNode->m_pRight != NULL)
{
dq.push_back(pNode->m_pRight);
}
}
}

BinaryTreeNode* ConstructBinaryTreeCore(int *startPreOrder, int *endPreOrder, int *startInOrder, int *endInOrder)
{
BinaryTreeNode *pRoot = new BinaryTreeNode;
pRoot->m_nValue = startPreOrder[0];
pRoot->m_pLeft = pRoot->m_pRight = NULL;

if (startPreOrder == endPreOrder)
{
if (startInOrder == endInOrder && *startInOrder == *endInOrder)
{
return pRoot;
}
else
{
return NULL;
}
}

int *current = startInOrder;

while (current <= endInOrder && *current != startPreOrder[0])
{
current++;
}

if ((current - startInOrder) > 0)
{
pRoot->m_pLeft = ConstructBinaryTreeCore(startPreOrder+1, startPreOrder+(current - startInOrder), startInOrder, current-1);
}

if ((endInOrder - current) > 0)
{
pRoot->m_pRight = ConstructBinaryTreeCore(startPreOrder+(current - startInOrder)+1, endPreOrder, current+1, endInOrder);
}

return pRoot;
}

BinaryTreeNode* ConstructBinaryTree(int preOrder[], int inOrder[], int n)
{
if (n <= 0)
{
return NULL;
}

return ConstructBinaryTreeCore(preOrder, preOrder+n-1, inOrder, inOrder+n-1);
}

int main()
{
int preOrder[7] = {1, 2, 4, 5, 3, 6, 7};
int inOrder[7] = {4, 2, 5, 1, 6, 3, 7};

BinaryTreeNode *pRoot;

pRoot = ConstructBinaryTree(preOrder, inOrder, 7);

PrintByLevel(pRoot);

system("pause");
return 0;
}