簡體   English   中英

使用C中的遞歸添加到完整的二叉樹

[英]Adding to a complete binary tree using recursion in C

我正在嘗試學習遞歸,所以我嘗試了一個程序來創建完整的二叉樹,然后打印其所有元素的總和,我自己編寫了插入部分,並且感到困惑的是我的指針變量"curr"指向一棵樹節點,為什么我能夠執行"curr = curr->left"因為它只是指向節點的指針。 不僅實際的樹節點還應該包含這些左右字段? 請給我一個關於新手疑問的提示。 我很驚訝我的程序可以完成這項工作。

謝謝 :)

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

struct node{
    int data;
    struct node *left,*right;
};

struct node *head = NULL;
struct node *curr = NULL;

void insert_Data(int val,struct node* curr){
    struct node *tempnode = (struct node*)malloc(sizeof(struct node));
    tempnode->data = val;
    tempnode->left = NULL;
    tempnode->right = NULL;
    if(head==NULL){
        head = tempnode;
        curr = head;
        printf("head element is : %d\n",head->data);
    }
    else{
        if(curr->left == NULL){
            curr->left = tempnode;
        }
        else if(curr->right == NULL){
            curr->right = tempnode;
        }
        else{
            curr = curr->left;
            insert_Data(val,curr);
        }
    }
}

//to test program
int sumNode(struct node* root ) {
  // if there is no tree, its sum is zero
  if( root == NULL ) {
    return 0 ;

  } else { // there is a tree
   printf("element is = %d\n",root->data);
    return root->data + sumNode( root->left ) + sumNode( root->right ) ;
  }
}

int main() {
    int arr[] = {1,2,3,4,5,6,7,8,9};
    int i;
    for(i=0;i<9;i++){
        insert_Data(arr[i],head);
    }
    int result = sumNode(head);
    printf("\n\n%d",result);
    return 0;
}

有關箭頭運算符->的含義,請參見C中有關此問題的箭頭運算符(->)用法

關於問題標題,我建議一個遞歸insert方法,該方法遵循從內到外的模式:

// in: the value to be inserted as new node
//     the head of the sub-tree that should contain the new node
// out: the new head of the subtree
struct node* insert_Data(int val, struct node* subtreeRoot);

只要您不重新平衡樹,這基本上就會導致以下行為:任何有效的subtreeRoot輸入都將返回自身,並在樹層次結構中的某個位置添加新值,而NULL輸入將返回新創建的節點作為輸出。

struct node* insert_Data(int val, struct node* subtreeRoot)
{
    if (subtreeRoot == NULL)
    {
        struct node *tempnode = (struct node*)malloc(sizeof(struct node));
        tempnode->data = val;
        tempnode->left = NULL;
        tempnode->right = NULL;
        return tempnode;
    }
    else if (val < subtreeRoot->data)
    {
        subtreeRoot->left = insert_Data(val, subtreeRoot->left);
    }
    else // val is bigger than the subtree root data
    {
        subtreeRoot->right = insert_Data(val, subtreeRoot->right);
    }
    return subtreeRoot;
}

使用方式如下:

head = insert_Data(arr[i], head);

目前,返回值僅有助於將NULL比較保持在一個位置。 但是如上所述,這種簽名和用法還允許使用更復雜的插入方法,其中子樹結構在插入時會完全改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM