赞
踩
二叉树的递归遍历:https://blog.csdn.net/weixin_51450101/article/details/122742243?spm=1001.2014.3001.5501
/*先序遍历二叉树的非递归算法(直接实现栈操作)*/ void PreOrder(BiTree bt) { //s[m]表示栈,top表示栈顶指针 BiTNode* s[Stack_Size]; int top = 0; BiTNode* p = bt; do { while (p != NULL) { if (top > Stack_Size) return; printf("%c ", p->data); top = top + 1; s[top] = p; p = p->LChild; } if (top != 0) { p = s[top]; top = top - 1; p = p->RChild; } } while (p != NULL || top != 0); }
/*中序遍历二叉树的非递归算法(直接实现栈操作)*/ void InOrder(BiTree bt) { //s[m]表示栈,top表示栈顶指针 BiTNode* s[Stack_Size]; int top = 0; BiTNode* p = bt; do { while (p != NULL) { if (top > Stack_Size) return; top = top + 1; s[top] = p; p = p->LChild; } if (top != 0) { p = s[top]; top = top - 1; printf("%c ", p->data); p = p->RChild; } } while (p != NULL || top != 0); }
/*后序遍历二叉树的非递归算法(直接实现栈操作)*/ void PostOrder(BiTree bt) { //s[m]表示栈,top表示栈顶指针 BiTNode* s[Stack_Size]; int top = 0; BiTNode* p = bt, * q = NULL; while (p != NULL || top != 0) { if (p != NULL) { if (top > Stack_Size) return; top = top + 1; s[top] = p; p = p->LChild; } else { p = s[top]; if (p->RChild == NULL || p->RChild == q) { //无右孩子结点或右孩子结点已遍历过 printf("%c ", p->data); q = p; top = top - 1; p = NULL; } else p = p->RChild; } } }
# include<stdio.h>
# include<malloc.h>
# define Stack_Size 50
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。