【发布时间】:2017-04-18 01:08:41
【问题描述】:
到目前为止足够简单的程序:由包含整数值的节点和指向节点左右分支的指针组成的二叉树。
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int val;
struct node *left;
struct node *right;
} Node;
void insert(Node *root, int val);
int main(void){
Node *root = NULL;
insert(root, 5);
insert(root, 3);
printf("%d\n", root->val);
return 0;
}
void insert(Node *root, int val){
if(root == NULL){ // Create tree if root is empty
root = malloc(sizeof(struct node));
root->val = val;
root->left = NULL;
root->right = NULL;
} else if(val < root->val){ // branch to left of tree if new value is less than root value
if(root->left == NULL){
root->left = malloc(sizeof(struct node));
}
root->left->val = val;
} else if(val > root->val){ // branch to right of tree if new value is greater than root value
if(root->right == NULL){
root->right = malloc(sizeof(struct node));
}
root->right->val = val;
}
}
无论出于何种原因,插入都很顺利。我可以输入 5 和 3(任意)都很好。但我无法打印出应该在 root->val 中的值“5”?该程序完全崩溃了。我是否忽略了什么?
【问题讨论】:
-
尝试在第一个
insert()之后打印root的指针值 - 这不是你想的那样...... -
我好像搞砸了。
-
你搞砸的一种方式是不做研究。 SO 上的所有链接列表/树帖子中约有一半存在“仅更新本地变量”问题。
标签: c binary-tree binary-search-tree