个人觉得借助栈或队列的非递归只是另一种形式的递归。当然这种方式对于效率的提高还是有好处的。
先序遍历很简单,根指针入栈,然后不断出栈,右孩子入栈,左孩子入栈:
- void pre_order(struct BiTNode *T, void (*visit)(TElemType e))
- {
- struct stack *s;
- struct BiTNode *p;
- if (T != NULL) {
- s = init_stack();
- push(s, T);
- while (! stack_empty(s)) {
- p = top(s);
- pop(s);
- visit(p->data);
- if (p->rchild != NULL) {
- push(s, p->rchild);
- }
- if (p->lchild != NULL) {
- push(s, p->lchild);
- }
- }
- }
- destory_stack(s);
- }
中序遍历:首先根指针入栈、遍历左子树,出栈,遍历右子树:
- void in_order(struct BiTNode *T, void (*visit)(TElemType e))
- {
- struct stack *s;
- struct BiTNode *p;
- p = T;
- s = init_stack();
- while (p != NULL || ! stack_empty(s)) {
- if (p != NULL) { /* push the root pointer, and traverse the left child tree */
- push(s, p);
- p = p ->lchild;
- }
- else { /* pop and visit the pointer, traverse the right child tree */
- p = top(s);
- pop(s);
- visit(p->data);
- p = p->rchild;
- }
- }
- destory_stack(s);
- }
后序遍历:根指针入栈、遍历左子树,根据右孩子的值判断是否出栈,遍历右子树:
- void post_order(struct BiTNode *T, void (*visit)(TElemType e))
- {
- struct stack *s;
- struct BiTNode *p, *pre;/* pre means recently visit */
- p = T;
- pre = NULL;
- s = init_stack();
- while (p != NULL || ! stack_empty(s)) {
- if (p != NULL ) {
- push(s, p);
- p = p->lchild;
- }
- else {
- p = top(s);
- if (p->rchild == NULL || p->rchild == pre) {
- visit(p->data);
- pop(s);
- pre = p;
- p = NULL;
- }
- else {
- p = p->rchild;
- }
- }
- }
- destory_stack(s);
- }
层次遍历:很简单,根指针入队,出队,左孩子入队,右孩子入队:
- void level_order(struct BiTNode *T, void (*visit)(TElemType e))
- {
- struct queue *q;
- struct BiTNode *p;
- p = T;
- q = init_queue();
- if (T != NULL) {
- en_queue(q, p);
- while(! queue_empty(q)) {
- p = gethead(q);
- de_queue(q);
- visit(p->data);
- if (p->lchild != NULL) {
- en_queue(q, p->lchild);
- }
- if (p->rchild != NULL) {
- en_queue(q, p->rchild);
- }
- }
- }
- destory_queue(q);
- }