您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法分析-查找二叉树

2008-11-21 08:57 113 查看
由于本人初学数据结构与算法,此写的为学习心得,希望园内的朋友给予指点。

查找二叉树的定义,所有节点的左子树均比该结点小,右子树均比该节点大。如下所示为一个正解的查找二叉树:

6

5 7

1 9

8 10

根据定义,查找二叉树的节点应包含一个存储数据,两个指针,分别指向节点的左、右子树,如下所示。

Code

#include <iostream>

#include <cstdlib>

#include <ctime>

#include "BTree.h"

using namespace std;

int main(int argc, char *argv[])

{

//随机生成一棵树

BTree<int> tree;

srand((unsigned)time(NULL));

for(int i=0; i<20; ++i)

{

tree.Insert(rand() / 20);

}

cout << "前序:" << endl;

tree.PreOrder();

cout << endl;

cout << "中序" << endl;

tree.InOrder();

cout << endl;

cout << "后序" << endl;

tree.PostOrder();

cout << endl;

cout << "层次" << endl;

tree.LevelOrder();

cout << endl;

if(tree.Find(14))

{

cout << "14 is in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

else

{

cout << "14 is not in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

if(tree.Find(30))

{

cout << "30 is in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

else

{

cout << "30 is not in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

if(tree.Find(3))

{

cout << "3 is in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

else

{

cout << "3 is not in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

if(tree.Find(5))

{

cout << "5 is in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

else

{

cout << "5 is not in the tree,search for " ;

tree.PrintStatic();

cout << endl;

}

return 0;

}

以上代码在本人电脑中测试通过,如发现问题与代码的不当之请告之本人。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: