数的遍历c++实现

来源:互联网 发布:java应聘笔试编程题 编辑:程序博客网 时间:2024/06/06 04:56
#include#include#ifndef BINARY_SEARCH_TREE#define BINARY_SEARCH_TREEusing namespace std;templateclass Stack:public stack{ public:T pop(){ T tmp = top(); stack::pop(); return tmp;}void push(T el){stack::push(el);}};template class Queue:public queue{public:T dequeue(){T tmp=front();queue::pop();return tmp;}void enqueue(const T& el){push(el);}};templateclass BSTNode{public:BSTNode(){left=right=0;} BSTNode(const T&el,BSTNode *l=0,BSTNode *r=0) { key=el;left=l;right=r; } T key; BSTNode *left,*right;};templateclass BST{BST(){root=0;}~BST(){clear();}void clear(){clear(root); root=0;}bool isEmpty()const{return root=0;}void preorder(){preorder(root);}void inorder(){inorder(root);}void postorder(){postorder(root);}T & search(const T &el)const{return serach(root,el);}void breadthFirst();void iterativePreorder();void iterativeInorder();void iterativePostorder();void deleteByMerging(BSTNode *&);void findAndDeleteMerging(const T&);void deleteByCopying(BSTNode* &);void balance(T *,int,int);protected:BSTNoderoot;void clear(BSTNode*);T *serach(BSTNode*,const T&)const;void preorder(BSTNode*);void inorder(BSTNode*);void postorder(BSTNode*);virtual void visit(BSTNode*p){cout<key<<' ';}};templateT *BST::serach(BSTNode* p,const T &el)const {while(p!=0)if(el==p->key)return &p->key;else if(elkey)p=p->key;else p=p->right;return 0;}templateclass BST::breadthFirst() {Queue*>queue;BSTNode*p=root;if(p!=0){queue.enqueue(p);while(!queue.empty()){p=queue.dequeue(); // 广度优先算法visit(p);if(p->left!=0)queue.enqueue(p->left);if(p->right!=0)queue.enqueue(p->right); }}}templatevoid BST::inorder(BSTNode*p) // 中序深度优先{if(p!=0){inorder(p->left);visit(p);inorder(p->right);}}templatevoid BST::preorder(BSTNode* p) // 先序 深度优先{if(p!=0){visit(p);preorder(p->left);preorder(p->right);}}void BST::postorder(BSTNode* p) // 后序 深度优先{if(p!=0){postorder(p->left);postorder(p->right);visit(p);}}templatevoid BST::iterativePreorder() // 先序 非递归 堆栈方式实现{stack *>travStack;BSTNode*p =root;if(p!=0){travStack.push(p);while(travStack.empty()){p=travStack.pop();visit(p); if(p->right!=0); travStack.push(p->right); if(p->left!=0); travStack.push(p->left);}}}templatevoid BST::iterativePostorder() //后序 遍历 堆栈方式实现{stack*>travStack;BSTNode*p=root,*q=root;while(p!=0){for(;p->left!=0;p=p->right)travStack.push(p); while(p!=0&&(p->right==0 ||p->right==q) { visit(p); q=p; return; p=travStack.pop(); } travStack.push(p); p=p->right;}} templatevoid BST::iterativeInorder() //中序遍历 堆栈方式实现 {Stack*>travStack;BSTNode *p=root;while(p!=0){while(p!=0){if(p->right)travStack.push(p->right);p=p->left;}p=travStack.pop();while(!travStack.empty()&& p->right==0){visit(p);p=travStack.pop();}visit(p);if(!travStack.empty()) p=travStack.pop();else p=0;}}#endif