添加红黑树的节点树以及树高度计算函数
This commit is contained in:
@@ -7,6 +7,9 @@
|
||||
#ifndef REDBLACKTREE_REDBLACKTREE_H_03
|
||||
#define REDBLACKTREE_REDBLACKTREE_H_03
|
||||
|
||||
#include <cstddef>
|
||||
#include <stack>
|
||||
|
||||
namespace ling {
|
||||
|
||||
enum Relation {
|
||||
@@ -145,6 +148,10 @@ namespace ling {
|
||||
// 查找最大结点:返回tree为根结点的红黑树的最大结点。
|
||||
const Node *maximum() const;
|
||||
|
||||
[[nodiscard]] size_t getSize() const;
|
||||
|
||||
[[nodiscard]] int getTreeHeight() const;
|
||||
|
||||
#define rb_parent(r) ((r)->parent)
|
||||
#define rb_color(r) ((r)->color)
|
||||
#define rb_is_red(r) ((r)->color==RED)
|
||||
@@ -156,6 +163,53 @@ namespace ling {
|
||||
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
int RedBlackTree<T>::getTreeHeight() const {
|
||||
const Node *current = getRoot();
|
||||
if (current == nullptr)
|
||||
return 0;
|
||||
std::stack<std::pair<const Node *, int>> stack;
|
||||
stack.push({current, 1});
|
||||
|
||||
int maxHeight = 0;
|
||||
while (!stack.empty()) {
|
||||
auto [node, height] = stack.top();
|
||||
stack.pop();
|
||||
if (node != nullptr) {
|
||||
maxHeight = std::max(maxHeight, height);
|
||||
if (node->right != nullptr) {
|
||||
stack.push({node->right, height + 1});
|
||||
}
|
||||
if (node->left != nullptr) {
|
||||
stack.push({node->left, height + 1});
|
||||
}
|
||||
}
|
||||
}
|
||||
return maxHeight;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
size_t RedBlackTree<T>::getSize() const {
|
||||
const Node *current = getRoot();
|
||||
std::stack<const Node *> stack;
|
||||
size_t size = 0;
|
||||
while (current != nullptr || !stack.empty()) {
|
||||
//走到最坐子树
|
||||
while (current != nullptr) {
|
||||
stack.push(current);
|
||||
current = current->left;
|
||||
}
|
||||
|
||||
//处理当前节点
|
||||
current = stack.top();
|
||||
stack.pop();
|
||||
size++;
|
||||
//处理右子树
|
||||
current = current->right;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
typename RedBlackTree<T>::Node const *RedBlackTree<T>::maximum() const {
|
||||
Node *tree = rootNode;
|
||||
|
||||
Reference in New Issue
Block a user