From acce44863f778533079b581a06f6a5d5ee0d7045 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=A9=BB=E9=AD=82=E5=9C=A3=E4=BD=BF?= Date: Fri, 6 Sep 2024 16:28:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=BA=A2=E9=BB=91=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E8=8A=82=E7=82=B9=E6=A0=91=E4=BB=A5=E5=8F=8A=E6=A0=91?= =?UTF-8?q?=E9=AB=98=E5=BA=A6=E8=AE=A1=E7=AE=97=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- include/RedBlackTree.h | 54 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/include/RedBlackTree.h b/include/RedBlackTree.h index 2234391..5ac481b 100644 --- a/include/RedBlackTree.h +++ b/include/RedBlackTree.h @@ -7,6 +7,9 @@ #ifndef REDBLACKTREE_REDBLACKTREE_H_03 #define REDBLACKTREE_REDBLACKTREE_H_03 +#include +#include + 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 + int RedBlackTree::getTreeHeight() const { + const Node *current = getRoot(); + if (current == nullptr) + return 0; + std::stack> 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 + size_t RedBlackTree::getSize() const { + const Node *current = getRoot(); + std::stack 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 RedBlackTree::Node const *RedBlackTree::maximum() const { Node *tree = rootNode;