数据结构 = 结构定义 + 结构操作
1 二叉树
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
1.1 结构定义
类似链表: 分为暴露在程序外部的与存储在内存内部的
1.1.1 (内部结构)存储在内存内部
typedef struct Node{
int data;
struct Node *lchild, *rchild;
} Node;
1.1.2 (外部结构)暴露在程序外部
typedef struct Tree {
int n;
Node* root;
} Tree;
1.2 结构操作
初始化/清除
Node *getNode(int val) {
Node *p = (Node *)malloc(sizeof(Node));
p->data = val;
p->lchild = p->rchild = NULL;
return p;
}
Tree* getTree() {
Tree *tree = (Tree *)malloc(sizeof(Tree));
tree->root = NULL;
tree->n = 0;
return tree;
}
void clearNode(Node *node) {
if (!node) return;
clearNode(node->lchild);
clearNode(node->rchild);
free(node);
return;
}
void clear(Tree* tree) {
if (!tree) return;
clearNode(tree->root);
free(tree);
return;
}
按照二叉搜索树的规则插入结点
Node* insertNode(Node* root, int val, int* inc) {
if (!root) {
*inc = 1;
return getNode(val);
}
if (root->data == val) return root;
if (root->data > val) root->lchild = insertNode(root->lchild, val, inc);
else root->rchild = insertNode(root->rchild, val, inc);