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

来源:互联网 发布:浏览记录监控软件 编辑:程序博客网 时间:2024/04/20 00:09
#include<iostream>#include<stack>#define N 7using 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;}

0 0
原创粉丝点击