如何根据一个字符串递归建立二叉树?

新手上路,请多包涵
node *c2(char *s){
    node *tem;
    if(*s == '#' || *s == '\0') tem = NULL;
    else{
        tem = (node*)malloc(sizeof(struct node));
        tem->data = *s;
        tem->left = NULL;
        tem->right = NULL;

        tem->left = c2(++s);
        tem->right = c2(++s);
    }
    return tem;
}

s是一个字符数组,这样建树有错吗?为什么输出的结果不对呢?谢谢大家

阅读 4.8k
2 个回答
tem->left = c2(++s);
tem->right = c2(++s);

构建完左子树后s的值只是加了1,在递归调用中并没有改变当前的s值。

tem->left = c2()这种写法并没让树节点真正链接起来。
改成这样吧

typedef struct BiTNode {
    char data;
    struct BiTNode *left, *right;
}BiTNode, *BiTree;

void createBiTree(BiTree &T) {
    char el = *s++;
    if (el == '#' || el == '\0') {
        T = NULL;
    } else {
        T = (BiTNode *)malloc(sizeof(BiTNode));
        T->data = el;
        createBiTree(T->left);
        createBiTree(T->right);
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题