在二叉树中找值为x的结点(假设所有结点的值都不一样)

#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
************

 

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值