【问题标题】:For my C code to construct a binary search tree and print the tree on its side is not printing anything?对于我的 C 代码来构造二叉搜索树并在其一侧打印树不是打印任何东西吗?
【发布时间】:2019-09-21 16:31:30
【问题描述】:

我正在尝试编写一个程序来构建二叉搜索树并在其一侧打印树。将用户的输入读取为整数序列,并输出基于深度缩进的树,每行有一个值。但是,我的代码正在运行,但没有在控制台上打印任何内容? 我认为我的插入功能可能有问题,但我不确定。

#include <stdio.h>
#include <stdlib.h> 
struct node {
  int data;
  struct node *left, *right;
};  
typedef struct node node;   
node *insert(node *t, int a){ //insert values in tree
  node* tmp= (node*)malloc(sizeof(node));;  
  if (t==NULL) {
      tmp->data = a;
      tmp->left = NULL;
      tmp->right = NULL;
      return(tmp);
    }
  else if (a < t->data)
      t->left = insert(t->left,a);
    else
      t->right = insert(t->right,a);    
  return(t);
}
void print( node *t, int depth) {
    int i;
    if (t == NULL) 
        return;         
    print(t->right, depth + 1); 
    for (i = 0; i < 4 * depth; ++i)
        printf(" ");            
    printf("%d\n", t->data);        
    print(t->left, depth + 1);
}   
int main() {
    node *root= NULL;
    int n,a,i;
    printf("Enter number of values "); //7
    scanf("%d", &n);    
    printf("\nEnter numbers "); //10 6 14 4 8 12 16
    for (i = 0; i < n; ++i) {
        scanf("%d", &a);
        insert(&root, a);
    }   
    print(root, 0); 
    return 0;
}
Input: 10 6 14 4 8 12 16
Expected output:
        16
    14
        12
10
        8
    6
        4

【问题讨论】:

  • 一个快速的问题,我看到你没有在任何地方分配insert() 的返回指针。所以root 始终为空。并且不要忘记free分配的内存。

标签: c pointers tree binary-tree nodes


【解决方案1】:

insert的签名是

node *insert(node *t, int a) // t is a pointer to node

但是你传递了一个指向节点的指针

insert(&root, a);

我想你想要

root = insert(root, a);

【讨论】:

  • 是的,很容易检测到带有警告的编译:) warning: passing argument 1 of ‘insert’ from incompatible pointer type insert(&amp;root, a); ,看看rapidtables.com/code/linux/gcc/gcc-wall.html,你会节省很多时间
  • 另外,考虑在最后使用destroy() 函数free()ing 节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多