#include<iostream>
#include<stack>
#define N 7
using namespace std;
typedef struct node
{
struct node *leftChild;
struct node *rightChild;
int data;
}BiTreeNode, *BiTree;
// 生成一个结点
BiTreeNode *createNode(int i)
{
BiTreeNode * q = new BiTreeNode;
q->leftChild = NULL;
q->rightChild = NULL;
q->data = i;
return q;
}
BiTree createBiTree()
{
BiTreeNode *p[N];
int i;
for(i = 0; i < N; i++)
p[i] = createNode(i + 1);
// 把结点连接成树
for(i = 0; i < N/2; i++)
{
p[i]->leftChild = p[i * 2 + 1];
p[i]->rightChild = p[i * 2 + 2];
}
return p[0];
}
BiTreeNode *findElement(BiTree T, int element)
{
if(NULL == T)
return NULL;
if(element == T->data)
return T;
BiTreeNode *p = findElement(T->leftChild, element);
if(NULL != p)
return p;
return findElement(T->rightChild, element);
}
int main()
{
BiTree T = createBiTree();
BiTreeNode *p;
p = findElement(T, 0);
cout << p << endl;
cout << "************" << endl;
p = findElement(T, 8);
cout << p << endl;
cout << "************" << endl;
p = findElement(T, 1);
cout << p->data << endl;
cout << p->leftChild->data << endl;
cout << p->rightChild->data << endl;
cout << "************" << endl;
p = findElement(T, 2);
cout << p->data << endl;
cout << p->leftChild->data << endl;
cout << p->rightChild->data << endl;
cout << "************" << endl;
p = findElement(T, 3);
cout << p->data << endl;
cout << p->leftChild->data << endl;
cout << p->rightChild->data << endl;
cout << "************" << endl;
p = findElement(T, 4);
cout << p->data << endl;
cout << p->leftChild << endl;
cout << p->rightChild << endl;
cout << "************" << endl;
p = findElement(T, 5);
cout << p->data << endl;
cout << p->leftChild << endl;
cout << p->rightChild << endl;
cout << "************" << endl;
p = findElement(T, 6);
cout << p->data << endl;
cout << p->leftChild << endl;
cout << p->rightChild << endl;
cout << "************" << endl;
p = findElement(T, 7);
cout << p->data << endl;
cout << p->leftChild << endl;
cout << p->rightChild << endl;
cout << "************" << endl;
return 0;
}
结果如下:
00000000
************
1
2
3
************
2
4
5
************
3
6
7
************
4
00000000
00000000
************
5
00000000
00000000
************
6
00000000
00000000
************
7
00000000
00000000
************