树(Tree)是一种重要的非线性数据结构,在计算机科学中广泛应用,如文件系统、数据库索引、解析表达式等。
树是一种层次结构的数据结构,由节点(Node) 组成,满足以下特点:
示例树结构:
A
/ \
B C
/ \ \
D E F
普通树的每个节点可以有任意多个子节点,例如文件系统中的目录结构。
每个节点最多有两个子节点,分别是左子节点(Left Child) 和 右子节点(Right Child)。
每个非叶子节点都有两个子节点,并且所有叶子节点在同一层。
除最后一层外,所有层的节点都填满,且最后一层的节点必须从左到右连续排列。
满足以下性质:
示例:
10
/ \
5 15
/ \ \
2 7 20
满足二叉搜索树的性质。
对二叉搜索树进行平衡,使任意节点的左、右子树的高度差不超过 1。
一种自平衡二叉搜索树,广泛应用于 STL 中的 map
、set
以及数据库索引。
#include
using namespace std;
// 二叉树节点结构
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 先序遍历(根 -> 左 -> 右)
void preOrder(TreeNode* root) {
if (root == nullptr) return;
cout << root->val << " ";
preOrder(root->left);
preOrder(root->right);
}
// 中序遍历(左 -> 根 -> 右)
void inOrder(TreeNode* root) {
if (root == nullptr) return;
inOrder(root->left);
cout << root->val << " ";
inOrder(root->right);
}
// 后序遍历(左 -> 右 -> 根)
void postOrder(TreeNode* root) {
if (root == nullptr) return;
postOrder(root->left);
postOrder(root->right);
cout << root->val << " ";
}
int main() {
// 构造一个简单的二叉树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
cout << "先序遍历: ";
preOrder(root);
cout << "\n中序遍历: ";
inOrder(root);
cout << "\n后序遍历: ";
postOrder(root);
return 0;
}
先序遍历: 1 2 4 5 3
中序遍历: 4 2 5 1 3
后序遍历: 4 5 2 3 1
// 插入节点
TreeNode* insert(TreeNode* root, int key) {
if (root == nullptr) return new TreeNode(key);
if (key < root->val)
root->left = insert(root->left, key);
else
root->right = insert(root->right, key);
return root;
}
// 查找节点
bool search(TreeNode* root, int key) {
if (root == nullptr) return false;
if (root->val == key) return true;
return key < root->val ? search(root->left, key) : search(root->right, key);
}
int main() {
TreeNode* root = nullptr;
root = insert(root, 10);
root = insert(root, 5);
root = insert(root, 15);
root = insert(root, 3);
cout << (search(root, 5) ? "找到 5" : "未找到 5") << endl;
cout << (search(root, 7) ? "找到 7" : "未找到 7") << endl;
return 0;
}
找到 5
未找到 7
操作系统的目录结构通常用树表示,每个目录可以包含多个子目录或文件。
数据库索引使用 B-树 或 B+树 来优化查询效率。
如解析 a + (b * c)
可用二叉树表示,进行计算。
用于分类、预测,如 ID3、C4.5 算法。
用于 IP 地址匹配,提高路由查询效率。