NYOJ 756 重建二叉树

来源:互联网 发布:php加密授权 编辑:程序博客网 时间:2024/04/30 05:23

题目链接
为什么我会觉得二叉树这么难呢?为什么我会觉得递归的程序比较难写呢?我想大概就是因为这些变量们循环来循环去的,很容易让我觉得混乱,理不清头绪,再加上都是字母表示的,有时候很容易思路就会断开,,题目一看算法很明确,,菜鸟想的都是先建树后遍历,建树肯定是递归,然而我却想不到如何去写这个递归的程序,哪些量是要递归改变的,然而我连左右递归都没想到,只觉得一筹莫展,不过自己照模板打了一遍,再来看这个题目,大概就是两个字符串加上二叉树的一些操作吧。。
参考链接
我敲的模板(二叉树的建立和遍历还是需要继续熟悉吧)

#include<stdio.h>#include<stdlib.h>#include<string.h>typedef struct node{    char num;    struct node *lchild,*rchild;}Node,*PNode;void buildTree(PNode *root,char *post,char *in,int len){    if(len==0)    {        *root=NULL;        return;    }    PNode node=(PNode)malloc(sizeof(Node));//分配新的空间    node->num=post[len-1];//节点值    node->lchild=node->rchild=NULL;//左右孩子赋值为空    *root=node;//根?    char *s=strchr(in,node->num);    int leftlen=strlen(in)-strlen(s);    int rightlen=len-leftlen-1;    buildTree(&(*root)->lchild,post,in,leftlen);    buildTree(&(*root)->rchild,post+leftlen,s+1,rightlen);}void bianliTree(PNode root){    if(root==NULL)        return;    printf("%c",root->num);    bianliTree(root->lchild);    bianliTree(root->rchild);}int main(){    char post[26],in[26];    while(~scanf("%s %s",post,in))    {        PNode root=NULL;//声明一个空树        buildTree(&root,post,in,strlen(in));        bianliTree(root);        printf("\n");    }    return 0;}
0 0
原创粉丝点击