二叉树的先序遍历的递归和非递归
操作方法
- 01
//队列非递归遍历需要 template<class NodeType> class Stack { public: Stack(){nIndex = 0;} ~Stack(){} //入栈 void Push(NodeType *p) { arr[nIndex] = p; ++nIndex; } //获取栈顶元素 NodeType *Top() { --nIndex; if (nIndex<0) { nIndex = 0; return NULL; } return arr[nIndex]; } bool IsEmpty() { return nIndex == 0; } private: NodeType *arr[100]; int nIndex;//栈顶的位置 }; struct Node { int nData; struct Node *pLchild; struct Node *pRchild; }; //递归遍历 void DG_BianLi(Node *pTree) { if (!pTree) { return; } printf("%d ",pTree->nData); DG_BianLi(pTree->pLchild); DG_BianLi(pTree->pRchild); } //非递归遍历 void FDG_BianLi(Node *pTree) { Node *pNode = pTree; Stack<Node> stack; while(pNode || !stack.IsEmpty()) { if (pNode) { printf("%d ",pNode->nData); stack.Push(pNode); pNode = pNode->pLchild; } else { pNode = stack.Top(); pNode = pNode->pRchild; } } } int _tmain(int argc, _TCHAR* argv[]) { //创建一个小树 Node node[5] = { {1,NULL,NULL}, {2,NULL,NULL}, {3,NULL,NULL}, {4,NULL,NULL}, {5,NULL,NULL} }; node[0].pLchild = &node[1]; node[0].pRchild = &node[4]; node[1].pLchild = &node[2]; node[2].pRchild = &node[3]; //DG_BianLi(node); FDG_BianLi(node); getchar(); return 0; }