您的位置:首页 > 其它

查找树(二叉树)的构建以及分层遍历

2013-04-02 20:40 357 查看
代码均通过vs2008编译运行

头文件代码:

#include <iostream>

#include <stack>//包含stack和queue,为了方便遍历数据存储

#include <queue>

struct BTree//定义查找树的结构

{

int m_data;

struct BTree* m_pLeft;

struct BTree* m_pRight;

};

struct BTree* insert(struct BTree* root,int& data)//查找树的生成,采用递归操作

{

if (root==NULL)

{

root = (struct BTree*)malloc( sizeof(struct BTree) );

root->m_data=data;

root->m_pLeft=NULL;

root->m_pRight=NULL;

}

else

{

if (root->m_data>data)

{

root->m_pRight=insert(root->m_pRight,data);

}

else

{

root->m_pLeft=insert(root->m_pLeft,data);

}

}

return root;

}

void show_tree(struct BTree* root)//输出树的内容,顺序输出

{

/* recursion */

if (root->m_pLeft!=NULL||root->m_pRight!=NULL)

{

if (root->m_pLeft!=NULL)

{

show_tree(root->m_pLeft);

}

if (root->m_pRight!=NULL)

{

show_tree(root->m_pRight);

}

}

/* backtracking */

printf("%d\t",root->m_data);

return;

}

std::stack<int> range_tree(struct BTree* root,std::stack<int>& int_stack)//在栈中存储树的数据,满足LIFO输出

{

if (root->m_pLeft!=NULL||root->m_pRight!=NULL)

{

if (root->m_pLeft!=NULL)

{

int_stack=range_tree(root->m_pLeft,int_stack);

}

if (root->m_pRight!=NULL)

{

int_stack=range_tree(root->m_pRight,int_stack);

}

}

/* backtracking */

int_stack.push(root->m_data);

return int_stack;

}

std::queue<int> queue_tree(struct BTree* root,std::queue<int>& int_queue)//在队列中存储树的数据,满足FIFO

{

if (root->m_pLeft!=NULL||root->m_pRight!=NULL)

{

if (root->m_pLeft!=NULL)

{

int_queue=queue_tree(root->m_pLeft,int_queue);

}

if (root->m_pRight!=NULL)

{

int_queue=queue_tree(root->m_pRight,int_queue);

}

}

/* backtracking */

int_queue.push(root->m_data);

return int_queue;

}





主文件:

#include "tree.h"

int main(void)

{

std::stack<int> int_value;

std::queue<int> int_queue;

struct BTree* number={0};//初始化

int i=0;

while (std::cin>>i)

{

number=insert(number,i);

}

show_tree(number);

std::cout<<std::endl;

int_value=range_tree(number,int_value);

std::stack<int>::size_type stack_cap = int_value.size();

for (std::stack<int>::size_type i=0;i!=stack_cap;++i)

{

std::cout<<int_value.top()<<"\t";

if (int_value.size()!=0)

{

int_value.pop();//注意要出栈

}

else break;

}

std::cout<<std::endl;

int_queue=queue_tree(number,int_queue);

std::queue<int>::size_type queue_cap = int_queue.size();

for (std::queue<int>::size_type iter=0;iter!=queue_cap;++iter)

{

std::cout<<int_queue.front()<<"\t";

int_queue.pop();//注意要出队



}

std::cout<<std::endl;

system("pause");

return NULL;

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