微软等公司数据结构面试题1

 

tree.h
typedef struct BSTreeNode {
int m_value;
struct BSTreeNode *m_left ;
struct BSTreeNode *m_right;
} bstTreeNode;
class ActTree{
public:
ActTree();
void InsertValue() ;
void DeleteValue() ;
void Sort();
void PrintTree();
void PrintNode(bstTreeNode *node);
void ChangeDoubleList();
void Change(bstTreeNode *node);
void addlist(bstTreeNode *node);
void PrintList();
private:
bstTreeNode *currentList;
bstTreeNode *root;
bstTreeNode *first;
};
tree.cpp
#include "tree.h"
#include <cstdlib>
#include <iostream>
ActTree::ActTree()
{
root = NULL;
first = NULL;
// std::cout<<"construction error!"<<std::endl;
}
void ActTree::InsertValue()
{
int temp,flag = 0;
std::cout<<"Input  ";
std::cin>>temp;
bstTreeNode *pnow  = root;
bstTreeNode *pparent  = root;
while( pnow ) {
if( pnow->m_value == temp ){
flag = 1;
pnow = NULL;
std::cout<<"%d has existed!"<<std::endl;
}
else if( pnow->m_value > temp ) {
pparent = pnow ;
pnow = pnow ->m_left ;
}
else {
pparent = pnow ;
pnow = pnow ->m_right ;
}
}
if(!flag) {
if( bstTreeNode *ptemp = (bstTreeNode *) malloc(sizeof (bstTreeNode))) {
ptemp->m_value = temp;
ptemp->m_left = ptemp->m_right = NULL;
if (pparent)
{
if( pparent->m_value > temp ) 
pparent->m_left =ptemp ;
else 
pparent->m_right =ptemp ;
}
else {
root = ptemp;
}
}
else
std::cerr<<"malloc failed!"<<std::endl;
}
}
void ActTree::PrintTree()
{
PrintNode(root);
}
void ActTree::PrintNode(bstTreeNode *node)
{
if( node ){
PrintNode(node->m_left);
std::cout<<node->m_value<<" ";
PrintNode(node->m_right);
}
}
void ActTree::addlist(bstTreeNode *node)
{
if (!first) {
first = node ;
currentList =first;
first->m_left = NULL;
first->m_right = NULL;
}
else {
currentList->m_right = node;
node->m_left =currentList;
node->m_right =NULL;
currentList = node;
}
}
void ActTree::Change(bstTreeNode *node)
{
if (node) {
Change(node->m_left);
bstTreeNode * right = node ->m_right;
addlist(node);
Change(right);
}
else
return ;
}
void ActTree::ChangeDoubleList()
{
this->Change(root);
}
void ActTree::PrintList()
{
bstTreeNode * node = first;
while(node) {
std::cout<<node->m_value<<"=";
node = node->m_right;
}
}
main.cpp
#include "tree.h"
#include <iostream>
int main()
{
ActTree test ;
int select;
//while (std::cin<<select )
test.InsertValue();
test.InsertValue();
test.InsertValue();
test.InsertValue();
test.PrintTree();
std::cout<<std::endl;
test.ChangeDoubleList();
test.PrintList();
getchar();
getchar();
return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值