打印二叉树期间的无限循环

时间:2013-10-25 19:40:04

标签: c binary-tree

这是我的代码,除了printInTree()

中的无限循环外,其工作几乎正确
struct node{
    char text[100];
    int count;
    struct node* left;
    struct node* right;
};

struct node* addNode(struct node* n,char w[]){
    int cond=0;
    if(n == NULL){
        n=malloc(sizeof(struct node));
        n->count=1;
        n->left=NULL;
        n->right=NULL;
        strcpy(n->text,w);
    }
    else if((cond=strcmp(w,n->text))==0){
        n->count++;
    }
    else if(cond>0){
        n->right=addNode(n->right,w);
    }
    else{
        n->left=addNode(n->left,w);
    }
    return n;
};

void printInTree(struct node* p){   
    while(p != NULL){                //infinite loop here.
        printInTree(p->left);
        printf("%3s - %d\n",p->text,p->count);
        printInTree(p->right);

    }
}

void b_treeDemo(){
    struct node *root=NULL;
    FILE* f=fopen("main.c","r");
    char word[100];
    while(1){
        if(getWord(f,word)>0){
            if(isalpha(word[0])){
                root=addNode(root,word);
            }
        }else{
            break;
        }
    }
    printInTree(root);
}

如何打破这个循环,以便它按顺序打印树。

4 个答案:

答案 0 :(得分:5)

p在循环中没有变化,会使它变得有限吗?你想做的可能是

if(!p) return;

而不是while循环。 (要首先理解递归,你需要理解递归)。

答案 1 :(得分:2)

您正在尝试以递归方式打印树,因此这就是您想要的:

void printInTree(struct node* p){   
    if (p == NULL) return;
    printInTree(p->left);
    printf("%3s - %d\n",p->text,p->count);
    printInTree(p->right);
}

当遇到NULL子节点时,递归调用将停止。你这里不需要while

答案 2 :(得分:1)

您似乎正在结合递归和迭代。在printInTree函数中,您使用递归来调用子节点上的相同函数,但是,您也可以在while循环内部使用递归,确保p != NULL。对于函数printInTree的任何给定调用,除非p == NULL,否则该调用将是无限的。

如果您将while更改为if,则代码应无限制地循环运行。

答案 3 :(得分:0)

p在while循环结束时不会改变(正如其他人指出的那样,应该是if语句)

相关问题