以下程序显示了如何在C程序中构建二叉树。它使用动态内存分配,指针和递归。二叉树是一个非常有用的数据结构,因为它允许在排序列表中进行高效插入,搜索和删除。由于这样的树本质上是一个递归定义的结构,所以递归编程是处理它的自然和有效的方式。为什么在这个编程中使用指针指针?
tree
empty
node left-branch right-branch
left-branch
tree
right-branch
tree
下面的代码:
#include <stdlib.h>
#include <stdio.h>
struct tree_el {
int val;
struct tree_el * right, * left;
};
typedef struct tree_el node;
void insert(node ** tree, node * item) {
if(!(*tree)) {
*tree = item;
return;
}
if(item->val<(*tree)->val)
insert(&(*tree)->left, item);
else if(item->val>(*tree)->val)
insert(&(*tree)->right, item);
}
void printout(node * tree) {
if(tree->left) printout(tree->left);
printf("%d\n",tree->val);
if(tree->right) printout(tree->right);
}
void main() {
node * curr, * root;
int i;
root = NULL;
for(i=1;i<=10;i++) {
curr = (node *)malloc(sizeof(node));
curr->left = curr->right = NULL;
curr->val = rand();
insert(&root, curr);
}
printout(root);
}
为什么使用指针到指针?
可否请你用4个空格缩进程序的每一行?这将使其格式正确。 – Edmund 2009-12-16 09:24:22
这是功课吗?它看起来像。 – 2009-12-16 09:47:05
nopes。我试图刷新我的指针概念,但坚持在这里 – emkrish 2009-12-16 09:56:45