文章目录
在本教程中,您将学习二叉树及其不同类型。此外,您还将找到C中二叉树的工作示例(C ++,Java和Python示例见原文)。
二叉树是一种树数据结构,其中每个父节点最多可以有两个子节点。
例如:在下图中,每个元素最多有两个子元素。
二叉树的类型
满二叉树(Full Binary Tree)
满二叉树是二叉树的一种特殊类型,其中每个父节点/内部节点都有两个或没有子节点。
完美二叉树(Perfect Binary Tree)
完美二叉树是一种二叉树,其中每个内部节点恰好有两个子节点,而所有叶节点都处于同一级别。
完全二叉树(Complete Binary Tree)
完全二叉树(Complete Binary Tree)就像全二叉树,但有两个主要区别
1.每个级别都必须完全填满
2.所有叶元素必须向左倾斜
3.最后一个叶元素可能没有正确的同级,即完全二叉树(Complete Binary Tree)不一定是满二叉树(Full Binary Tree)。
退化树或病态树
退化/病态树是有一个单独孩子的树,孩子或左或右。
斜二叉树
斜二叉树是一种病态/退化树,其中树由左节点或右节点控制。因此,有两种类型的斜二叉树:左斜二叉树和右斜二叉树。
平衡二叉树
它是一种二叉树,其中每个节点的左子树和右子树之间的差值为0或1。
二叉树表示法
二叉树的节点由一个包含数据部分和两个指向同一类型的结构指针表示。
struct node
{
int data;
struct node *left;
struct node *right;
};
C示例
// Tree traversal in C
#include <stdio.h>
#include <stdlib.h>
struct node {
int item;
struct node* left;
struct node* right;
};
// Inorder traversal
void inorderTraversal(struct node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ->", root->item);
inorderTraversal(root->right);
}
// Preorder traversal
void preorderTraversal(struct node* root) {
if (root == NULL) return;
printf("%d ->", root->item);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// Postorder traversal
void postorderTraversal(struct node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ->", root->item);
}
// Create a new Node
struct node* createNode(value) {
struct node* newNode = malloc(sizeof(struct node));
newNode->item = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
// Insert on the left of the node
struct node* insertLeft(struct node* root, int value) {
root->left = createNode(value);
return root->left;
}
// Insert on the right of the node
struct node* insertRight(struct node* root, int value) {
root->right = createNode(value);
return root->right;
}
int main() {
struct node* root = createNode(1);
insertLeft(root, 2);
insertRight(root, 3);
insertLeft(root->left, 4);
printf("Inorder traversal \n");
inorderTraversal(root);
printf("\nPreorder traversal \n");
preorderTraversal(root);
printf("\nPostorder traversal \n");
postorderTraversal(root);
}
二叉树应用
- 轻松快速地访问数据
- 用于路由器算法
- 实现堆数据结构
- 语法树
参考文档
https://www.programiz.com/dsa/binary-tree