二叉树的遍历算法分为三种,根据对父节点的遍历顺序分为先序遍历、中序遍历以及后序遍历。其中可使用递归方式以及非递归方式,递归方式程序非常简单,但是效率相对较低,在非递归i方式中,借助栈来对数据进行存储。
定义树中节点的数据结构如下所示:
typedef struct _node {
struct _node *left_child;
struct _node *right_child;
ctype_t data;
}node, *tree; //二叉树节点结构
二叉树的递归遍历和非递归遍历算法如下所示:
void preorder_recursion(tree root) { if (NULL != root) { printf("%d/t", root->data); //根 preorder_recursion(root->left_child); //左子树 preorder_recursion(root->right_child); //右子树 } } void preorder_nonrecursive(tree root) { tree stack[100]; int top = 0; tree p=root; while (NULL != p || top > 0) { while (NULL != p) { printf("%d/t", p->data); stack[top++] = p; p=p->left_child; } p = stack[--top]; p = p->right_child; } } void inorder_recursion(tree root) { if (NULL != root) { inorder_recursion(root->left_child); //左子树 printf("%d/t", root->data); //根 inorder_recursion(root->right_child); //右子树 } } void inorder_nonrecursive(tree root) { tree stack[100]; int top = 0; tree p = root; while (NULL != p || top > 0) { while (NULL != p) { stack[top++] = p; p = p->left_child; } p = stack[--top]; printf("%d/t", p->data); p = p->right_child; } } void postorder_recursion(tree root) { if (NULL != root) { postorder_recursion(root->left_child); postorder_recursion(root->right_child); printf("%d/t", root->data); } } void postorder_nonrecursive(tree root) { tree stack[100]; int top=0; tree p = root; tree lastvist = NULL; while (NULL != p || top > 0) { while (NULL != p) { stack[top++] = p; p = p->left_child; } p = stack[top-1]; if (NULL == p->right_child || lastvist == p->right_child) { printf("%d/t", p->data); --top; lastvist = p; p = NULL; } else { p = p->right_child; } } }