二叉树遍历小技巧

来源:互联网 发布:mac打不出双引号 编辑:程序博客网 时间:2024/04/29 15:17

二叉树的遍历的小技巧


如题,我们知道了一个二叉树的前序遍历与中序遍历,现在相求它的后序遍历(其实只是写给自己看,怕以后会忘了)

#include <stdio.h>#include <string.h>#include <stdlib.h>void houxu(struct tree *root){    if(root)    {        houxu(root -> left);        houxu(root -> right);        printf("%c",root -> data);    }}struct node{    char data;    struct node *left,*right;};struct node *creat(int n,char *str1,char *str2)//二叉树的重建与后续遍历输出{    struct node *root;    int i;    if(n==0)        return NULL;    root=(struct node *)malloc(sizeof(struct node));    root->data=str1[0];//找到根节点,根节点为str1(先序序列)的第一个    for(i=0;i<n;i++)//找到str2(中序序列)的根节点的位置    {        if(str2[i]==str1[0])            break;    }    root->left=creat(i,str1+1,str2);//(左子树的长度,左子树在str1中开始位置的地址,左子树在str2中开始位置的地址)    root->right=creat(n-i-1,str1+i+1,str2+i+1);//(右子树的长度,右子树在str1中开始位置的地址,右子树在str2中开始位置的地址)    return root;};int main(){    int n;    char str1[1100],str2[1100];    scanf("%s",str1);    scanf("%s",str2);    n=strlen(str1);    struct node *root = creat(n,str1,str2);    houxu(root);    printf("\n");    return 0;}

没错,我的第一反应就是这样,先根据前序遍历中序遍历构建出一个这样的二叉树,然后再根据以前学的后序遍历输出再把它后序遍历输出来,但实际上这里可以节省一步

#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{    char data;    struct node *left,*right;};struct node *creat(int n,char *str1,char *str2)//二叉树的重建与后续遍历输出{    struct node *root;    int i;    if(n==0)        return NULL;    root=(struct node *)malloc(sizeof(struct node));    root->data=str1[0];//找到根节点,根节点为str1(先序序列)的第一个    for(i=0;i<n;i++)//找到str2(中序序列)的根节点的位置    {        if(str2[i]==str1[0])            break;    }    root->left=creat(i,str1+1,str2);//(左子树的长度,左子树在str1中开始位置的地址,左子树在str2中开始位置的地址)    root->right=creat(n-i-1,str1+i+1,str2+i+1);//(右子树的长度,右子树在str1中开始位置的地址,右子树在str2中开始位置的地址)    printf("%c",root->data);//后序遍历输出    return root;};int main(){    int n;    char str1[1100],str2[1100];    scanf("%s",str1);    scanf("%s",str2);    n=strlen(str1);    creat(n,str1,str2);    printf("\n");    return 0;}

没错,就是在它的二叉树构建里面,我们可以直接把这个后序遍历直接输出来,因为这个二叉树的构建核心思想就是通过递推把它的根找到,找完左边的再找右边的,然后再返回上一根节点,没错,这就和后序遍历的规则一样了,先找左边的,再找右边的,最后回到根,所以我们在构建这个二叉树的时候就可以顺着把它的后序遍历顺序输出来了(代码小白,如有错误,欢迎指出)

0 0
原创粉丝点击