小编Amb*_*S J的帖子

如何在C中删除二叉树中的元素?

我试图理解二叉树中节点的删除.这是我从教程中找到的代码片段,它解释了相同的内容.

该节点如下所示:

struct node
{
  int key_value;
  struct node *left;
  struct node *right;
};
Run Code Online (Sandbox Code Playgroud)

资料来源:http://www.cprogramming.com/tutorial/c/lesson18.html

    void destroy_tree(struct node *leaf)
    {
      if( leaf != 0 )
      {
          destroy_tree(leaf->left);
          destroy_tree(leaf->right);
          free( leaf );
      }
    }
Run Code Online (Sandbox Code Playgroud)

我怀疑这个free(leaf)部分.我的意思是,作者声称这将以递归方式从最左下角开始删除所有节点.但是,free(leaf)不仅仅是释放叶子指针的内存吗?是不是所有节点仍然连接?清算是如何进行的?

c free binary-tree pointers

5
推荐指数
1
解决办法
1110
查看次数

为什么此链接列表会无限期地打印最后一个元素?

我正在完成一个Hackerrank挑战,包括将元素添加到链表并打印它.

输入具有以下格式:一组整数,其中第一个元素给出大小,其余元素是列表的组成部分.

我用Java完成了挑战,但我无法在C中完成.输入4 2 3 4 1应打印2 3 4 1,但我编码的这个片段给了我1 1 1 1 1 1 ... .{truncated}

我的方法:声明一个Node类型的新结构temp(数据输入为数据字段,下一个字段为NULL),然后以head为起点遍历链表,当它到达最后一个元素时,更改最后一个元素的下一个字段到当前元素的地址.

码:

 #include <stdlib.h>
 #include <stdio.h> 

   typedef struct Node{
   int data;
   struct Node* next;
    }Node;

 Node* insert(Node *head,int data)
  {       
    Node temp = {data, NULL} ;

     if (head == NULL)
      { head =&temp;
        return head;
      }

     else{

    Node* current = head ;
    while(current->next !=NULL)
      current = current->next ;

      current->next = &temp;

      return head;
       }
   }

void display(Node *head)
{
Node …
Run Code Online (Sandbox Code Playgroud)

c pointers linked-list

1
推荐指数
1
解决办法
76
查看次数

为什么此代码段显示编译错误?

我收到了这个编译问题,我无法弄清楚原因.有人可以帮忙吗?

    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    int n = scan.getInt() ;
    System.out.println(factorial(n)) ;


int factorial(int a){
        if (a==0) 
            return 1;
        else 
            return (a*factorial(a-1));
    }}
Run Code Online (Sandbox Code Playgroud)

Post Edit注意:我不知道在main()中不能声明另一个函数.在外面写它,它工作得很好.

java compiler-errors

-4
推荐指数
1
解决办法
49
查看次数

标签 统计

c ×2

pointers ×2

binary-tree ×1

compiler-errors ×1

free ×1

java ×1

linked-list ×1