/* 二叉樹前中後/層次遍歷的遞歸與非遞歸形式 */ //*************** void preOrder1(BinaryTreeNode* pRoot) { if(pRoot==NULL) return; cout<<pRoot->value; if(pRoot->left!=NULL) preOrder1(pRoot->left); if(pRoot->right!=NULL) preOrder1(pRoot->right); } void preOrder2(BinaryTreeNode* pRoot) { stack<BinaryTreeNode*> s; BinaryTreeNode *p=pRoot; if(pRoot==NULL) return; while(p!=NULL||!s.empty()) { while(p!=NULL) { cout<<p->value<<" "; s.push(p); p=p->left; } if(!s.empty()) { p=s.top(); s.pop(); p=p->right; } } } void preOrder2(BinaryTreeNode* pRoot){ if(pRoot==NULL) return; stack<BinaryTreeNode*> s; s.push(root); BinaryTreeNode* p; while(!s.empty()){ p = s.top(); cout<<p->data;//遍歷根結點 s.pop(); if(p>right){ s.push(p->right); //先將右子樹壓棧 } if(p->left){ s.push(p->left); //再將左子樹壓棧 } } } //***************** //中序遍歷 void inOrder1(BinaryTreeNode* pRoot) { if(pRoot==NULL) return; if(pRoot->left!=NULL) inOrder1(pRoot->left); cout<<pRoot->value; if(pRoot->right!=NULL) inOrder1(pRoot->right); } void inOrder2(BinaryTreeNode* pRoot) { stack<BinaryTreeNode*> s; BinaryTreeNode *p=pRoot; if(pRoot==NULL) return; while(p!=NULL||!s.empty()) { while(p!=NULL) { s.push(p); p=p->left; } if(!s.empty()) { p=s.top(); cout<<p->value<<" "; s.pop(); p=p->right; } } } //***************** //後序遍歷 void postOrder1(BinaryTreeNode* pRoot) { if(pRoot==NULL) return; postOrder1(pRoot->left); postOrder1(pRoot->right); cout<<pRoot->value<<" "; } void postOrder2(BinaryTreeNode* pRoot) { stack<BinaryTreeNode*> s; BinaryTreeNode *cur; BinaryTreeNode *pre=NULL;//記錄上一個輸出的節點 s.push(pRoot);//根結點入棧 while(!s.empty()) { cur=s.top(); if((cur->left==NULL&&cur->right==NULL)||(pre!=NULL&&(pre==cur->left||pre==cur->right))) { //左孩子和右孩子同時爲空,或者當前結點的左孩子或右孩子已經遍歷過了 cout<<cur->value<<" "; s.pop(); pre=cur; } else { if(cur->right!=NULL) s.push(cur->right); if(cur->left!=NULL) s.push(cur->left); } } } //***************** //層次遍歷,使用隊列 void PrintFromTopToBottom(BinaryTreeNode* pRoot) { if(pRoot == NULL) return; deque<BinaryTreeNode *> dequeTreeNode; dequeTreeNode.push_back(pRoot); while(dequeTreeNode.size()) { BinaryTreeNode *pNode = dequeTreeNode.front(); dequeTreeNode.pop_front(); cout<<pNode->m_nValue<<" "; if(pNode->m_pLeft) dequeTreeNode.push_back(pNode->m_pLeft); if(pNode->m_pRight) dequeTreeNode.push_back(pNode->m_pRight); } } //深度優先遍歷~先序遍歷 void dfs(BinaryTreeNode* root){ stack<BinaryTreeNode* *> nodeStack; nodeStack.push(root); Node *node; while(!nodeStack.empty()){ node = nodeStack.top(); cout<<node->data;//遍歷根結點 nodeStack.pop(); if(node->rchild){ nodeStack.push(node->rchild); //先將右子樹壓棧 } if(node->lchild){ nodeStack.push(node->lchild); //再將左子樹壓棧 } } } //廣度優先遍歷~層次遍歷 void bfs(BinaryTreeNode* root){ queue<BinaryTreeNode* *> nodeQueue; nodeQueue.push(root); Node *node; while(!nodeQueue.empty()){ node = nodeQueue.front(); nodeQueue.pop(); cout<<node->data;//遍歷根結點 if(node->lchild){ nodeQueue.push(node->lchild); //先將左子樹入隊 } if(node->rchild){ nodeQueue.push(node->rchild); //再將右子樹入隊 } } }