【问题标题】:C program to insert/delete nodes, having difficulty runningC程序插入/删除节点,运行困难
【发布时间】:2017-04-26 06:04:14
【问题描述】:

我有一个作业,我应该在其中编写插入/删除树结构的函数,但我在实际正确执行程序时遇到了困难。这是骨架代码:

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);
}

输出应该是这样的:

项目>: 猫 - | ./bintree abc xyz 2>/dev/null

abc

我们

asd

zxc

我们

按顺序打印二叉树

节点是asd

节点是qwe

节点是zxc

项目>:

由于某种原因,尽管在编写了我的插入函数并执行了程序之后,我在成功运行程序的“按顺序打印树”部分时遇到了麻烦,而它不是一个无限循环,要求输入。有什么想法吗?

【问题讨论】:

  • 请修正你的缩进。

标签: c tree


【解决方案1】:

打印二叉树的一般算法是(伪代码):

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);
    }
}

【讨论】:

  • 你的插入函数是什么样子的?
  • 感谢您的回答!问题是,即使帐户中没有插入功能,我也无法正确执行程序。即使将“Insert(buf)”部分替换为“printf("%s","s");”之类的内容,在使用“cat - | ./bintree abc xyz 2>/dev /null" 来执行。
猜你喜欢
  • 2015-12-24
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多