1.建立二叉树。
二叉树如图所示
暴力建树(不推荐使用,太复杂)
#include <stdio.h>
#include <stdlib.h>
//定义结点
typedef struct node {
int data;
struct node* left;
struct node* right;
}Node;
int main(){
//用typedef了struct,并起名字为NODE以后可以简便一点声明一个结点
//struct node n1;
//struct node n1;
Node n1;
Node n2;
Node n3;
Node n4;
n1.data=5;
n2.data=6;
n3.data=7;
n4.data=8;
n1.left = &n2; //因为left是一个指针,所以必须是指向一个地址,'&'表示这个结点的地址
n1.right= &n3;
n2.left = &n4;
n2.right= NULL; //记得NULL要大写
n3.left = NULL;
n3.rihgt= NULL;
n4.right= NULL;
return 0;
}
2. 先序遍历、中序遍历、后序遍历
void preorder(Node* node){
if(node != NULL){
printf("%d", node->data);//node在这里是一个指针,所以用->,而不是.
preorder(node->left);
preorder(node->right);
}
}
/*在主函数调用 preorder()时候,调用的是一个指针类型
因此preorder(&n1),
因为n1是一个Node实体,所以n1前要加'&'表示n1的地址
*/
void inorder(Node* node){
if(node != NULL){
inorder(node->left);
printf("%d", node->data);
inorder(node->right);
}
}
void postorder(Node* node){
if(node != NULL){
postorder(node->left);
postorder(node->right);
printf("%d", node->data);
}
}
3. 动态建立二叉树
上面建立二叉树,虽然只有四个节点,但是代码已经特别长特别麻烦,因此接下来使用动态建立二叉树
二叉树在实际使用上一般是构建一个二叉搜索树(BST:Binary Search Tree)来使用,关于二叉搜索树的定义自行查阅,就是 左节点<根节点<右节点
#include <stdio.h>
#include <stdlib.h>
//定义结点
typedef struct node {
int data;
struct node* left;
struct node* right;
}Node;
/*为了以后方便访问一棵树
只要访问树的根节点就可,因此直接定义一棵树*/
typedef struct {
Node* root;
}Tree;
void insert(Tree* tree, int value) {//往一棵树中插入一个value
Node* node=malloc(sizeof(Node));
node -> data = value;
node -> left = NULL;
node -> right = NULL;
if(tree ->root == NULL){
tree -> root = node; //如果树空,直接插入当根节点
}
else{
Node* temp = tree -> root;//用temp代表value
while (temp != NULL){
//插入左边
if(value < temp -> data){
if (temp -> left == NULL)
temp->left = node; //如果temp左边为空,直接插入
}
else{
temp=temp->left;
}
}
//插入右边
else{
if (temp -> rihgt == NULL)
temp-> right= node; //如果temp右边边为空,直接插入
}
else{
temp=temp->right;
}
}
}
int main(){
int arr[7] = {6 ,3 ,8 ,2 ,5 ,1 ,7};
Tree tree;
tree.root = NULL;//空树
for(int i=0;i<7;i++){
insert(&tree, arr[i]);//若要检查创建的树是否正确,调用先序遍历和中序遍历即可
}
}
4. 判断树高,用递归
int get_height(Node* node){
if(node == NULL ){ //递归出口
return 0;
}
else {
int left_h = get_height(node->left); //左边树高度
int right_h = get_height(node->right);//右边树高度
int max = left_h;
if(right_h>max){
max = right_h;
}
return max + 1; //加上根节点
}
}
5. 找到最大值
//BST里面找最大节点的话一般就是找最右边就是了
int get_maximum(Node* node){
if(node = NULL){
return -1;
}
else{
int m1 = get_maximum(node -> left);
int m2 = get_maximum(node -> right);
int m3 = node -> data; //自己是m3
int max = m1;
if (m2>max){ max = m2; }
if (m3>max){ max = m3; }
return max;
}
}
以上文字均为本人对B站Up主 正月点灯笼的视频做的笔记,仅用于自学笔记用。