这是算法导论中二叉树搜索的一个题
二叉树如图所示
c++代码
#include<iostream>
#define N 7
using namespace std;
//定义节点
class node
{
public:
int data;
node *leftChild;//指针
node *rightChild;
};
typedef node *BiTree;//等价
node *createNode(int value)//创建节点,返回类型指针型,所以加*
{
node * q = new node;
q->leftChild = NULL;//leftChild指针为空
q->rightChild = NULL;
q->data = value;
return q;
}
BiTree createBiTree()
{
node *p[N] = {NULL};
int array[6]={6,5,7,2,5,8};//输入的二叉树
for(int i=0;i<6;++i)
p[i] = createNode(array[i]);
for(int i = 0; i < N/2; i++)
{
p[i]->leftChild = p[i * 2 + 1];
p[i]->rightChild = p[i * 2 + 2];
}
return p[0];
}
//访问节点中的数据
int visit(BiTree tree)
{
return tree->data;
}
// 先序遍历
void preorderTreeWalk(BiTree tree)
{
if(tree)
{
cout << visit(tree) << " ";
preorderTreeWalk(tree->leftChild);
preorderTreeWalk(tree->rightChild);
}
}
// 中序遍历
void inorderTreeWalk(BiTree tree)
{
if(tree)
{
inorderTreeWalk(tree->leftChild);
cout << visit(tree) << " ";
inorderTreeWalk(tree->rightChild);
}
}
// 后序遍历
void postorderTreeWalk(BiTree tree)
{
if(tree)
{
postorderTreeWalk(tree->leftChild);
postorderTreeWalk(tree->rightChild);
cout << visit(tree) << " ";
}
}
int main()
{
BiTree tree = createBiTree();
cout << "先序遍历结果为:";
preorderTreeWalk(tree);
cout << endl;
cout << "中序遍历结果为:";
inorderTreeWalk(tree);
cout << endl;
cout << "后序遍历结果为:";
postorderTreeWalk(tree);
cout << endl;
return 0;
}
运行结果