我想学习递归,所以我尝试了一个程序来创建一个完整的二叉树,然后打印其所有元素的总和,我自己写了插入部分,我困惑的是我的指针变量"curr"
它指向一个树节点,为什么我能够做"curr = curr->left"
,因为它只是一个指向节点的指针。不仅应该在实际的树节点中包含这些左右字段吗?只要给我一个关于这个新手的疑问。我很惊讶我的计划能够完成这项工作。添加到一个完整的二叉树使用递归C
谢谢:)
#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;
}
'curr'是一个指向'node'结构实例的指针。 'node'结构的成员有'left'和'right'。我不确定你的困惑来自哪里? –
感谢您的快速回复@some程序员哥们,其实我的困惑是我们创建的指向实际节点的节点指针是否也包含这些字段作为实际节点呢? –
也许这有助于:curr-> left与(* curr).left相同。指针不包含任何字段。它只是指向那个结构。 –