二叉树的各种遍历 #include <stdio.h> #include <malloc.h> #include <stack> #include <queue> #include "stack.h" using std::stack; using std::queue; typedef struct _node { int value; _node* pLChild; _node* pRChild; int visited; //用于树的后续非递归排序 }Node,*Tree; //创建树 void CreateTree(Tree* tree); //非递归前序遍历 void PreOrder(Tree tree); //非递归中序遍历 void InOrder(Tree tree); //非递归后序遍历 void PostOrder(Tree tree); //按层遍历 void LevelOrder(Tree tree); //递归前序遍历 void PreOrderNoRec(Tree tree); //递归中序遍历 void InOrderNoRec(Tree tree); //递归后序遍历 void PostOrderNoRec(Tree tree); //获得树的深度 int GetDepth(Tree tree); int main() { Tree tree; CreateTree(&tree); printf("%d ",GetDepth(tree)); return 0; } void CreateTree(Tree* tree) { int value; scanf("%d",&value); if(value == -1) *tree = NULL; else { *tree = (Tree)malloc(sizeof(Node)); if(!(*tree)) return; (*tree)->value = value; (*tree)->visited = 0; CreateTree(&(*tree)->pLChild); CreateTree(&(*tree)->pRChild); } } void PreOrder(Tree tree) { if(tree == NULL) return ; else { printf("%d ",tree->value); PreOrder(tree->pLChild); PreOrder(tree->pRChild); } } void InOrder(Tree tree) { if(tree == NULL) return ; else { PreOrder(tree->pLChild); printf("%d ",tree->value); PreOrder(tree->pRChild); } } void PostOrder(Tree tree) { if(tree == NULL) return ; else { PreOrder(tree->pLChild); PreOrder(tree->pRChild); printf("%d ",tree->value); } } void Destroy(Tree tree) { } /***************************************************************************** 首先需要一个栈,从树的根节点开始访问,然后访问左孩子并加入到栈中,然后继续向 左访问,只到把所有的左边节点都访问玩,然后从栈里弹出一节点,继续上述访问。 *****************************************************************************/ void PreOrderNoRec(Tree tree) { stack<Node*> sta; Node* pNode = tree; while(pNode || !sta.empty()) { while(pNode) { printf("%d ",pNode->value); sta.push(pNode); pNode = pNode->pLChild; } if(!sta.empty()) { pNode = sta.top(); sta.pop(); pNode = pNode->pRChild; } } } void InOrderNoRec(Tree tree) { stack<Node*> sta; Node* pNode = tree; while(pNode || !sta.empty()) { while(pNode) { sta.push(pNode); pNode = pNode->pLChild; } if(!sta.empty()) { pNode = sta.top(); sta.pop(); printf("%d ",pNode->value); pNode = pNode->pRChild; } } } void PostOrderNoRec(Tree tree) { Node* p,*q; p = tree; q = NULL; stack<Node*> sta; while(p||!sta.empty()) { if(p&&p->visited==0) { sta.push(p); p=p->pLChild; } else { p = sta.top(); sta.pop(); //右孩子不为空且没有访问 if(p->pRChild && p->pRChild->visited==0) { q=p; p=p->pRChild; //留着以后访问 sta.push(q); continue; } printf("%d",p->value); p->visited=1; } } } void LevelOrder(Tree tree) { if(tree == NULL) { printf("the tree is null........./n"); return ; } queue<Node*> que; Node* pNode = tree; que.push(pNode); while(!que.empty()) { pNode = que.front(); que.pop(); printf("%d ",pNode->value); if(pNode->pLChild) que.push(pNode->pLChild); if(pNode->pRChild) que.push(pNode->pRChild); } } int GetDepth(Tree tree) { if(tree == NULL) return 0; int nl = GetDepth(tree->pLChild); int nr = GetDepth(tree->pRChild); if(nl > nr) return nl + 1; else return nr + 1; }