写一段平衡二叉树中深度优先搜索的代码,使用C++实现
时间: 2024-05-13 14:18:26 浏览: 138
这是基本数据结构及其算法的C++实现,涉及单链表、双链表、栈 、二叉树、并查集、哈夫曼树、平衡二叉树、二叉搜索树等.zip
以下是平衡二叉树中深度优先搜索的代码实现,使用C++语言:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class AVLTree {
public:
AVLTree() : root(nullptr) {};
~AVLTree() {}
void insert(int val) {
root = insert(root, val);
}
void dfs() {
dfs(root);
}
private:
TreeNode* root;
TreeNode* insert(TreeNode* node, int val) {
if (node == nullptr) {
return new TreeNode(val);
}
if (val < node->val) {
node->left = insert(node->left, val);
}
else if (val > node->val) {
node->right = insert(node->right, val);
}
// 更新平衡因子
node->height = max(getHeight(node->left), getHeight(node->right)) + 1;
int balanceFactor = getBalanceFactor(node);
// 平衡维护
if (balanceFactor > 1 && getBalanceFactor(node->left) >= 0) {
return rightRotate(node);
}
if (balanceFactor < -1 && getBalanceFactor(node->right) <= 0) {
return leftRotate(node);
}
if (balanceFactor > 1 && getBalanceFactor(node->left) < 0) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balanceFactor < -1 && getBalanceFactor(node->right) > 0) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
void dfs(TreeNode* node) {
if (node == nullptr) {
return;
}
cout << node->val << " ";
dfs(node->left);
dfs(node->right);
}
int getHeight(TreeNode* node) {
if (node == nullptr) {
return 0;
}
return node->height;
}
int getBalanceFactor(TreeNode* node) {
if (node == nullptr) {
return 0;
}
return getHeight(node->left) - getHeight(node->right);
}
TreeNode* rightRotate(TreeNode* y) {
TreeNode* x = y->left;
TreeNode* T3 = x->right;
x->right = y;
y->left = T3;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
return x;
}
TreeNode* leftRotate(TreeNode* x) {
TreeNode* y = x->right;
TreeNode* T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
};
int main() {
AVLTree tree;
tree.insert(10);
tree.insert(20);
tree.insert(30);
tree.insert(40);
tree.insert(50);
tree.insert(25);
tree.dfs();
return 0;
}
```
阅读全文