在 C 中递归创建和遍历二叉树 [英] Create and traverse a binary tree recursively in C

查看:41
本文介绍了在 C 中递归创建和遍历二叉树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个二叉树并通过前序遍历来遍历它,我使用递归方法.这些代码可以编译但不能正常运行,我发现它可能无法完成CreateBitree()函数,但我不知道问题出在哪里.

I want to create a binary tree and traverse it by preorder traversal, and I use recursive method. These code can be compiled but can not run correctly, and I found it maybe can not finish the CreateBitree() function, but I don't know where the problem is.

#include <stdio.h>
#include <malloc.h>

typedef struct BiNode{
    int data;
    struct BiNode *lchild;
    struct BiNode *rchild;    //left and right child pointer
}BiNode;

int CreateBiTree(BiNode *T);
int TraverseBiTree(BiNode *T);

int main() {
    BiNode *t;
    CreateBiTree(t);
    TraverseBiTree(t);
    return 0;
}

int CreateBiTree(BiNode *T) {          //create a binary tree by preorder traversal
    char tmp;
    scanf("%c", &tmp);
    if(tmp == ' ')
    T = NULL;
    else {
        T = (BiNode *)malloc(sizeof(BiNode));
        T -> data = tmp;
        CreateBiTree(T -> lchild);
        CreateBiTree(T -> rchild);
    }
    return 1;
}

int TraverseBiTree(BiNode *T) {        //traverse a binary tree by preorder traversal
    if(T != NULL) {
        printf("%c\n", T -> data);
        TraverseBiTree(T -> lchild);
        TraverseBiTree(T -> rchild);
    }
    return 1;
}

比如,当我输入一个像ABC##DE#G##F###"(#"表示空格)这样的预排序序列,然后它仍然让我输入时,我认为TraverseBiTree() 函数尚未执行.

For example, when I input a preorder sequence like "ABC##DE#G##F###"("#"means space), and then it still let me to input, I think the TraverseBiTree() function hasn't been executed.

推荐答案

将指针值分配给函数内的指针不会在该函数范围之外产生任何影响.这样做:

An assignment of a pointer value to a pointer within a function does not have any effect outside the scope of that function. Doing this:

int CreateBiTree(BiNode *T) { 
  /* ... */
  T = NULL;

与这样做相同:

int func(int i) { 
  /* ... */
  i = 0;

在这些情况下需要指向参数的指针:

A pointer to the argument is necessary in these cases:

int CreateBiTree(BiNode **T) { 
  /* ... */
  T[0] = NULL;  // or... *T = NULL;

对初始代码进行一些更改:

With some changes to the initial code:

int main() {
    BiNode *t; 
    CreateBiTree(&t);
    TraverseBiTree(t);
    return 0;
}

int CreateBiTree(BiNode **T) {          //create a binary tree by preorder traversal
    char tmp;
    scanf("%c", &tmp);
    if(tmp == ' ')
    T[0] = NULL;
    else {
        T[0] = (BiNode *)malloc(sizeof(BiNode));
        T[0]-> data = tmp;
        CreateBiTree(&(T[0]->lchild));
        CreateBiTree(&(T[0]->rchild));
    }   
    return 1;
}

这篇关于在 C 中递归创建和遍历二叉树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆