先序遍历——递归 void preorder(node* root) { if (root) printf(“%d/n”, root->value); else return; preorder(root->left); preorder(root->right); } 先序遍历——非递归 void preoder(node* root) { element* theStack; void* data; node* curNode; CreateStack(&theStack); Push(&theStack, root); while(Pop(&theStack, &data)) { curNode = (node*) data; if (curNode) { printf(“%d/n”, curNode->value); Push(&theStack, curNode->right); Push(&theStack, curNode->left); } } DeleteStack(theStack); } 中序遍历——递归 void InOrder(BiTree T) { if (T == NULL) return; if (T->lchild) InOrder(T->lchild); printf("%d/n", T->value); if (T->rchild) InOrder(T->rchild); } 中序遍历——非递归 void InOrder(BiTree T) { InitStack(S); p = T; while(p || !StackEmpty(S)) { if (p) { Push(S, p); p = p->lchild; } else { Pop(S, p); printf("%d/n", p->value); p = p->rchild; } } } 后序遍历——递归 void PostOrder(BiTree T) { if (T == NULL) return; if (T->lchild) PostOrder(T->lchild); if (T->rchild) PostOrder(T->rchild); printf("%d/n", T->value); } 后序遍历——非递归 TreeNodeElement::TreeNodeElement()//构造函数 { _value = -1; _l = NULL; _r = NULL; _tag = false; } TreeNodeElement::TreeNodeElement(int value) { _value = value; _l = NULL; _r = NULL; _tag = false; } void PostRetriveATreeWithoutRecurve(TreeNode root,void (* visit)(TreeNode)) { stack<TreeNode> tree; while ((root != NULL) || (!tree.empty())) { while (root != NULL) { tree.push(root); root = root->_l; } if (!tree.empty()) { root = tree.top(); if (root->_tag) //可以访问 { visit(root); tree.pop(); root = NULL; //第二次访问标志其右子树也已经遍历 } else { root->_tag = true; root = root->_r; } } } }