This commit is contained in:
2025-09-15 21:12:04 +08:00
commit 3f58f483ff
144 changed files with 5298 additions and 0 deletions

66
dataStruct/Tree/Tree.h Normal file
View File

@@ -0,0 +1,66 @@
//
// Created by 李洋 on 2023/8/14.
//
#ifndef LEECODE_C_TREE_H
#define LEECODE_C_TREE_H
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
#include <iostream>
#include <random>
#include <queue>
TreeNode *creatRandomTree(int size) {
if (size == 0) {
return nullptr;
}
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(1, 100);
std::queue<int> Q;
std::queue<TreeNode *> T;
for (int i = size; i > 0; --i) {
Q.push(dis(gen));
std::cout << Q.back() << " ";
}
std::cout << std::endl;
TreeNode *head = new TreeNode(Q.front());
T.push(head);
Q.pop();
while (!Q.empty()) {
if (T.front()->left != nullptr && T.front()->right != nullptr) {
T.pop();
}
TreeNode *temp = new TreeNode(Q.front());
Q.pop();
if (T.front()->left == nullptr) {
T.front()->left = temp;
T.push(temp);
continue;
}
if (T.front()->right == nullptr) {
T.front()->right = temp;
T.push(temp);
}
}
return head;
}
#endif //LEECODE_C_TREE_H

View File

@@ -0,0 +1,56 @@
//
// Created by 李洋 on 2023/9/6.
//
#ifndef LEECODE_C_TREESTACK_H
#define LEECODE_C_TREESTACK_H
#pragma once
#include <iostream>
#include <vector>
#include "./Tree.h"
class TreeStack {
private:
std::vector<TreeNode *> data;
public:
// 入栈操作
void push(TreeNode *value) {
data.push_back(value);
}
// 出栈操作
TreeNode *pop() {
if (!isEmpty()) {
TreeNode *topValue = data.back();
data.pop_back();
return topValue;
} else {
std::cerr << "Error: Stack is empty." << std::endl;
return nullptr; // 可以根据需要返回其他值或抛出异常
}
}
// 获取栈顶元素
TreeNode *top() const {
if (!isEmpty()) {
return data.back();
} else {
std::cerr << "Error: Stack is empty." << std::endl;
return nullptr; // 可以根据需要返回其他值或抛出异常
}
}
// 检查栈是否为空
bool isEmpty() const {
return data.empty();
}
// 获取栈的大小
size_t size() const {
return data.size();
}
};
#endif //LEECODE_C_TREESTACK_H