#include<iostream> using namespace std; #define MAX 100 struct BSTreeNode { int m_nValue; // value of node int m_level; BSTreeNode *m_pLeft; // left child of node BSTreeNode *m_pRight;// right child of node BSTreeNode *m_pParent; }; struct Queue{ struct BSTreeNode node[MAX]; int front, rear; }; void InitQ(Queue*& q){ q->front = q->rear = 0; } void EnQ(Queue* q, BSTreeNode *node){ if(q->front == (q->rear+1)%MAX){ cout<<"Queue is full."<<endl; return; } q->node[q->rear] = *node; q->rear += 1; } BSTreeNode* DeQ(Queue* q){ if(q->front == q->rear){ cout<<"Queue is empty."<<endl; return NULL; } BSTreeNode* p = &(q->node[q->front]); q->front += 1; return p; } void InsertBSTree(BSTreeNode*& pNode, int value){ if(NULL == pNode){ pNode = new BSTreeNode; pNode->m_nValue = value; pNode->m_level = 1; pNode->m_pLeft = pNode->m_pRight = NULL; pNode->m_pParent = NULL; }else{ if(value > pNode->m_nValue){ InsertBSTree(pNode->m_pRight, value); pNode->m_pRight->m_pParent = pNode; pNode->m_pRight->m_level = pNode->m_level+1; }else{ InsertBSTree(pNode->m_pLeft, value); pNode->m_pLeft->m_pParent = pNode; pNode->m_pLeft->m_level = pNode->m_level+1; } } } void BSTree2Queue(Queue*& q, BSTreeNode* pNode){ if(pNode == NULL) return; EnQ(q, pNode); while(q->front != q->rear){ BSTreeNode* p = DeQ(q); if(p->m_pLeft != NULL || p->m_pRight != NULL){ if(p->m_pLeft != NULL){ EnQ(q, p->m_pLeft); } if(p->m_pRight != NULL){ EnQ(q, p->m_pRight); } } } } void DispBSTree(BSTreeNode* pNode){ Queue* q = new Queue; InitQ(q); BSTree2Queue(q, pNode); q->front = 0; BSTreeNode* p; while(q->front != q->rear){ p = DeQ(q); cout<<p->m_nValue<<","; } cout<<endl; delete q; } void SearchForSum(BSTreeNode* pNode, int& s, int sum){//采用中序遍历的方式 if(pNode == NULL){ return; } s += pNode->m_nValue; SearchForSum(pNode->m_pLeft, s, sum); if(pNode->m_pLeft != NULL) s -= pNode->m_pLeft->m_nValue; SearchForSum(pNode->m_pRight, s, sum); if(pNode->m_pRight != NULL) s -= pNode->m_pRight->m_nValue; if(s == sum){ BSTreeNode* tmp = pNode; cout<<"从上到下搜索和为"<<sum<<"的逆序为:"; while(tmp){ cout<<tmp->m_nValue<<" "; tmp = tmp->m_pParent; } cout<<endl; } } void DestroyBSTree(BSTreeNode* pNode){ if(pNode == NULL){ return; } BSTreeNode* tmp = pNode; DestroyBSTree(pNode->m_pLeft); DestroyBSTree(pNode->m_pRight); delete tmp; } int main(){ int value[6] = {12, 10, 5, 6 ,11, 21}; BSTreeNode* pNode = NULL; for(int i = 0; i < 6 ; i++){ InsertBSTree(pNode, value[i]); } DispBSTree(pNode); int s = 0; SearchForSum(pNode, s, 33); BSTreeNode* pDbList = NULL; DestroyBSTree(pNode); return 0; }