二叉树的遍历
二叉树的遍历可以使用递归,循环的方式遍历,一下列出了使用栈和队列的方式循环遍历二叉树的方式。
#include "stdafx.h" #include <stack> #include <queue> using namespace std; struct TreeNode { TreeNode() { memset(this, 0, sizeof(*this)); } TreeNode* pLeft; TreeNode* pRight; int m_nValue; }; /* 递归遍历 */ void TreeOrder(TreeNode* root) { if (NULL == root) { return ; } printf("%d ", root->m_nValue); TreeOrder(root->pLeft); TreeOrder(root->pRight); } /* 使用栈循环遍历 */ void TreeOrderStack(TreeNode* root) { if (NULL == root) { return ; } stack<TreeNode*> s; s.push(root); while (!s.empty()) { TreeNode* pNode = s.top(); s.pop(); printf("%d ",pNode->m_nValue); if (NULL != pNode->pLeft) { s.push(pNode->pLeft); } if (NULL != pNode->pRight) { s.push(pNode->pRight); } } } /* 使用队列循环遍历 */ void TreeOrderQueue(TreeNode* root) { if (NULL == root) { return ; } queue<TreeNode*> q; q.push(root); while (!q.empty()) { TreeNode* pNode = q.front(); q.pop(); printf("%d ", pNode->m_nValue); if (NULL != pNode->pLeft) { q.push(pNode->pLeft); } if (NULL != pNode->pRight) { q.push(pNode->pRight); } } } int _tmain(int argc, _TCHAR* argv[]) { return 0; }