C语言数据结构拉练----二叉树

本文探讨了C语言中二叉树的数据结构,包括内部和外部结构的定义,介绍了二叉搜索树的创建及二叉树广义表达式的创建方法,通过例程详细阐述了结构操作,如初始化、插入节点和遍历等。
摘要由CSDN通过智能技术生成

数据结构 = 结构定义 + 结构操作

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);
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值