树的遍历:dfs:深度遍历。bfs:广度遍历。
dfs:深度遍历
前序遍历,递归和迭代
递归:
void displyTree(tree * root)
{
if(root == NULL)
{
return;
}
printf("%d\n",root->val);
displyTree(root->left);
displyTree(root->right);
return;
}
迭代:先,中,后序遍历
void displyTree1(tree * root)
{
//模拟递归时的栈
stack *st = (stack *)malloc(sizeof(stack));
int top = -1;
//后序遍历:tree * pre = NULL;
/**
*先遍历左子树,到左底时,栈回弹上一个结点,查看结点的右子树
*
*
* 两种情况
* 当回弹的右结点也是空时,在栈内右结点的情况下,while继续循环top,继续弹栈
* 当回到跟结点时,栈为空,看右子树是否为空
*/
while(root != NULL || top > -1)
{
//遍历左子树
while(root != NULL)
{
st->stk[++top] = root;
//先序在此打印,即压栈就输出
printf("%d\n",root->val);
root = root->left;
}
//当左子树见底,往上回一个结点,观察结点的右子树
root = st->stk[top--];
//中序在此打印,回栈时是第二次经过该结点
//printf("%d\n",root->val);
/**
* 后序遍历两种情况:
* 1.右子树为空,直接打印
* 2.第三次经过该结点
* 需要增加一段代码将结点再次压栈
*/
// if(root->right == NULL || root->right == pre)
// {
// printf("%d\n",root->val);
// pre = root;
// root = NULL;
// }
// else
// {
// st->stk[++top] = root;
// root = root->right;
// }
root = root->right;
}
}
bfs:程序遍历
void bfsTree(tree *root)
{
tree * queue[2000];
int head = 0;
int tail = 0;
queue[tail++] = root;
while(head < tail)
{
//如何让层序遍历一层层的输出
//count 即可以记录层数又可以记录每层个数
int count = 0;
//last表示一层入队完毕后,最后一个的位置。
int last = tail;
while(head < last)
{
root = queue[head++];
printf("%d\n",root->val);
if(root->left != NULL)
{
queue[tail++] = root->left;
}
if(root->right != NULL)
{
queue[tail++] = root->right;
}
}
}
return;
}
翻转二叉树:
void dfsTransTree(tree * root)
{
if(root == NULL)
{
return;
}
tree * temp = root->left;
root->left = root->right;
root->right = temp;
dfsTransTree(root->left);
dfsTransTree(root->right);
return;
}
void dfsTransTree1(tree *root)
{
stack * st = (stack *)malloc(sizeof(stack));
st->top = -1;
while(root != NULL || st->top > -1)
{
//遍历左子树
while(root != NULL)
{
//先序处理结点
tree * temp = root->left;
root->left = root->right;
root->right = temp;
st->stk[++st->top] = root;
root = root->left;
}
root = st->stk[st->top--];
root = root->right;
}
return;
}
void bfsTransTree(tree * root)
{
tree * queue[1000];
int head = 0;
int tail = 0;
queue[tail++] = root;
while(head < tail)
{
int count = 0;
int last = tail;
while(head < last)
{
root = queue[head++];
tree * temp = root->left;
root->left = root->right;
root->right = temp;
if(root->left != NULL)
{
queue[tail++] = root->left;
}
if(root->right != NULL)
{
queue[tail++] = root->right;
}
}
}
return;
}