今天去面试了,有2道题没做出来,发现自己做题真的不行啊,晚上恶补。
1 二叉树分层遍历
二叉树遍历,要求从上往下遍历每一层,在每一层里从左往右遍历。题目里提示用队列,一直没想出来队列怎么用,后来自己想一下,直接用2个链表就搞定了,一个链表存储上一层结点,另外一个链表存储下一层结点。
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
typedef struct BinaryTreeNode BTNode;
struct BinaryTreeNode
{
int value;
BTNode *pLeft;
BTNode *pRight;
};
typedef struct List List;
struct List
{
BTNode *pNode;
List *pNext;
};
BTNode* newNode(int value)
{
BTNode *p = (BTNode*)malloc(sizeof(BTNode));
p->value = value;
p->pLeft = NULL;
p->pRight = NULL;
return p;
}
void insertNode(BTNode *pNode, int value)
{
assert(pNode);
if( value<pNode->value )
{
if(pNode->pLeft)
{
insertNode(pNode->pLeft, value);
}
else
{
pNode->pLeft = newNode(value);
}
}
else
{
if(pNode->pRight)
{
insertNode(pNode->pRight, value);
}
else
{
pNode->pRight = newNode(value);
}
}
}
void PrintNode(BTNode *pNode)
{
if(pNode)
{
printf("%d ",pNode->value);
PrintNode(pNode->pLeft);
PrintNode(pNode->pRight);
}
}
List* addListNode(BTNode *pNode)
{
List *p = (List*)malloc(sizeof(List));
p->pNode = pNode;
p->pNext = NULL;
return p;
}
void PrintByLine(BTNode *pNode)
{
assert(pNode);
List *pList1;
List *pList2;
List *p;
List *pIndex;
pList1 = (List*)malloc(sizeof(List));
pList2 = (List*)malloc(sizeof(List));
pList1->pNode = pNode;
pList1->pNext = NULL;
pList2->pNext = NULL;
while(1)
{
pIndex = pList2;
//遍历上一层结点,并输出
for(p=pList1; p!=NULL; p=p->pNext)
{
printf("%d ",p->pNode->value);
//输出的时候把下一层结点添加到pList2
if( p->pNode->pLeft!=NULL )
{
pIndex->pNext = addListNode(p->pNode->pLeft);
pIndex = pIndex->pNext;
}
if( p->pNode->pRight!=NULL )
{
pIndex->pNext = addListNode(p->pNode->pRight);
pIndex = pIndex->pNext;
}
}
//把上一层更新为下一层结点
pList1 = pList2->pNext;
pList2->pNext = NULL;
if(!pList1)
{
break;
}
}
}
void bt_test(void)
{
int a[]= {4, 47, 9, 1,
2, 10, 11, 33,
31,8 , 10, 17,
3, 4 , 56 ,55};
int i;
BTNode *pHead = newNode(a[0]);
for(i=1; i<sizeof(a)/sizeof(a[0]); i++)
{
insertNode(pHead, a[i]);
}
//PrintNode(pHead);
PrintByLine(pHead);
}
2 两柱香问题
有2柱香,质量分布不均匀,每柱香烧完要1小时,怎么确定15分钟的时间。
不会,直接问百度,关键的是用其中一炷香点2头,另外一炷香点一头,等其中一柱烧完后,另一柱还剩半小时,然后再点燃另一头,烧完就是15分钟。