C程序插入/删除节点,运行困难

时间:2017-04-25 21:45:28

标签: c tree

我有一个赋值,我应该写函数来插入/删除树结构,但是我实际上很难正确执行程序。这是骨架代码:

typedef struct tree tree;

#define MAXWORD 26

struct tree{
struct tree *b4;
struct tree *after;
char word[MAXWORD];
};

void Insert(char *);
void Delete(char *);

#ifndef MAIN
extern tree *root;
#endif

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAIN 1
#include "tree.h"
void printtree();
tree *root=NULL;

main(int argc, char **argv)
{
tree *node;
char buf[MAXWORD];
extern tree *root;
tree *p;

while((scanf("%s",buf))>0)
    Insert(buf);
while(argc-->1)
    Delete(argv[argc]);

printf("Print binary tree in order\n");
if(root!=NULL)
    printtree(root);
}

void printtree(tree *root){

if(root->b4!=NULL)
    printtree(root->b4);
printf("Node is %s \n",root->word);
if (root->after!=NULL)
    printtree(root->after);
}

,输出应该是这样的:

项目&gt;:cat - | ./bintree abc xyz 2&gt; / dev / null

ABC

QWE

ASD

ZXC

QWE

按顺序打印二叉树

节点是asd

节点是qwe

节点是zxc

项目&GT;:

出于某种原因,虽然在编写了我的插入函数并执行程序之后,我无法成功运行程序中的“打印树顺序”部分而不需要无限循环,请求输入。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

要打印二叉树,通用算法是(伪代码):

def inOrder_treeWalk(node) //define function that takes a node
    if(node)  //if the node is not Null
        inOrder_treeWalk(node.left) //recursive call with left child
        print node.key //print the key of this frame
        inOrder_treeWalk(node.right) //recursive call with right child

编辑:使用你拥有的东西

void printtree(tree *node){
    if(node){
        printtree(node->b4);
        printf("Node is %s \n", node->word);
        printtree(node->after);
    }
}