Java的红黑树测试代码

时间: 2023-11-07 12:38:34 浏览: 40
很高兴为您解答Java的红黑树测试代码。以下是一个简单的Java红黑树测试代码示例: import java.util.TreeMap; public class RedBlackTreeTest { public static void main(String[] args) { TreeMap<Integer, String> map = new TreeMap<Integer, String>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); map.put(4, "Four"); map.put(5, "Five"); System.out.println(map); } } 这段代码使用了Java中的TreeMap类作为示例红黑树,通过put()方法向红黑树中添加元素。运行结果将会按照键的顺序输出元素。 请问您还有其他问题吗?
相关问题

java 红黑树代码

### 回答1: java 红黑树是一种二叉搜索树,其中的每个节点都具有颜色属性,要么是红色,要么是黑色。红黑树的节点颜色可以是"红色"或"黑色"。这种树遵循以下几条规则: 1. 每个节点要么是红色,要么是黑色。 2. 根节点是黑色。 3. 每个叶子节点都是黑色的空节点(NIL节点)。 4. 如果一个节点是红色的,则它的子节点必须是黑色的。 5. 对于任意节点而言,其到叶子节点的每条路径都包含相同数目的黑色节点。 在 Java 中,可以使用 java.util.TreeMap 类来实现红黑树。这个类实现了映射接口,允许将键映射到值。它使用红黑树来维护映射关系,保证映射关系有序。 下面是一个简单的示例,展示了如何使用 TreeMap 类将字符串映射到整数: ```java import java.util.TreeMap; public class RedBlackTreeExample { public static void main(String[] args) { // 创建一个 TreeMap 对象 TreeMap<String, Integer> map = new TreeMap<>(); // 向 TreeMap 中添加映射关系 map.put("Apple", 10); map.put("Banana", 20); map.put("Orange", 30); map.put("Mango", 40); // 输出 TreeMap 中的映射 ### 回答2: 红黑树是一种自平衡的二叉搜索树,它保持在O(log n)时间内对插入、删除和查找等操作的性能。下面是一个Java实现的红黑树代码示例: ```java // 定义红黑树的节点 class Node { int key; Node parent; Node left; Node right; int color; } // 定义红黑树 class RedBlackTree { private Node root; private Node TNULL; // 构造函数 public RedBlackTree() { TNULL = new Node(); TNULL.color = 0; TNULL.left = null; TNULL.right = null; root = TNULL; } // 插入节点 public void insert(int key) { Node node = new Node(); node.parent = null; node.key = key; node.left = TNULL; node.right = TNULL; node.color = 1; // 新插入的节点为红色 Node y = null; Node x = this.root; while (x != TNULL) { y = x; if (node.key < x.key) { x = x.left; } else { x = x.right; } } node.parent = y; if (y == null) { root = node; } else if (node.key < y.key) { y.left = node; } else { y.right = node; } if (node.parent == null){ node.color = 0; return; } if (node.parent.parent == null) { return; } fixInsert(node); } // 修正插入导致的红黑树性质被破坏 private void fixInsert(Node node) { Node uncle; while (node.parent.color == 1) { if (node.parent == node.parent.parent.right) { uncle = node.parent.parent.left; if (uncle != null && uncle.color == 1) { uncle.color = 0; node.parent.color = 0; node.parent.parent.color = 1; node = node.parent.parent; } else { if (node == node.parent.left) { node = node.parent; rightRotate(node); } node.parent.color = 0; node.parent.parent.color = 1; leftRotate(node.parent.parent); } } else { uncle = node.parent.parent.right; if (uncle != null && uncle.color == 1) { uncle.color = 0; node.parent.color = 0; node.parent.parent.color = 1; node = node.parent.parent; } else { if (node == node.parent.right) { node = node.parent; leftRotate(node); } node.parent.color = 0; node.parent.parent.color = 1; rightRotate(node.parent.parent); } } if (node == root) { break; } } root.color = 0; } // 左旋转 private void leftRotate(Node x) { Node y = x.right; x.right = y.left; if (y.left != TNULL) { y.left.parent = x; } y.parent = x.parent; if (x.parent == null) { this.root = y; } else if (x == x.parent.left) { x.parent.left = y; } else { x.parent.right = y; } y.left = x; x.parent = y; } // 右旋转 private void rightRotate(Node x) { Node y = x.left; x.left = y.right; if (y.right != TNULL) { y.right.parent = x; } y.parent = x.parent; if (x.parent == null) { this.root = y; } else if(x == x.parent.right) { x.parent.right = y; } else { x.parent.left = y; } y.right = x; x.parent = y; } // 打印红黑树的中序遍历结果 public void printTree(Node node) { if (node == TNULL) { return; } printTree(node.left); System.out.print(node.key + " "); printTree(node.right); } } // 测试 public class Main { public static void main(String[] args) { RedBlackTree rbTree = new RedBlackTree(); rbTree.insert(55); rbTree.insert(10); rbTree.insert(5); rbTree.insert(2); rbTree.insert(8); rbTree.insert(15); rbTree.insert(16); System.out.println("红黑树中序遍历结果:"); rbTree.printTree(rbTree.root); } } ``` 以上是一个简单的红黑树的Java代码实现,其中包括插入节点、修正插入导致的红黑树性质被破坏、左旋转、右旋转等操作。在测试部分,插入了一些节点,并打印了红黑树的中序遍历结果。 红黑树的代码实现相对复杂,但是它的自平衡性质让它在各种操作下具有较好的性能。希望以上的代码示例能对你理解红黑树的实现有所帮助。

Java红黑树代码实现

### 回答1: Java红黑树是一种自平衡二叉搜索树,它是在二叉查找树的基础上添加了一些限制,以保证树的平衡。红黑树的着色性质,即每个节点要么是红色的,要么是黑色的,并且有以下几条性质: 1. 每个节点要么是红色的,要么是黑色的。 2. 根节点是黑色的。 3. 每个叶子节点都是黑色的。 4. 如果一个节点是红色的,那么它的子节点一定是黑色的。 5. 对于任意一个节点,从该节点到其子孙节点的所有路径上包含相同数目的黑色节点。 下面是一个Java红黑树的代码实现: ``` public class RedBlackTree { private static final boolean RED = true; private static final boolean BLACK = false; private class Node { int key; Node left; Node right; boolean color; public Node(int key, boolean color) { this.key = key; this.color = color; } } private Node root; public void put(int key) { root = put(root, key); root.color = BLACK; } private Node put(Node h, int key) { if (h == null) { return new Node(key, RED); } if (key < h.key) { h.left = put(h.left, key); } else if (key > h.key) { h.right = put(h.right, key); } else { h.key = key; } if (isRed(h.right) && !isRed(h.left)) { h = rotateLeft(h); } if (isRed(h.left) && isRed(h.left.left)) { h = rotateRight(h); } if (isRed(h.left) && isRed(h.right)) { flipCol ### 回答2: 红黑树是一种自平衡的二叉搜索树,它的实现方法比较复杂。下面是一个简单的Java红黑树代码实现示例: ```java // 定义红黑树节点 class Node { int data; // 节点数据 Node left; // 左子节点 Node right; // 右子节点 Node parent; // 父节点 boolean isRed; // 是否是红色节点 public Node(int data) { this.data = data; this.left = null; this.right = null; this.parent = null; this.isRed = true; // 默认新插入的节点为红色 } } // 定义红黑树 class RedBlackTree { private Node root; // 根节点 // 插入节点 public void insert(int data) { Node newNode = new Node(data); if (root == null) { root = newNode; root.isRed = false; // 根节点为黑色 } else { Node current = root; // 从根节点开始搜索插入位置 Node parent; while (true) { parent = current; if (data < current.data) { // 插入值小于当前节点值 current = current.left; if (current == null) { parent.left = newNode; newNode.parent = parent; fixInsert(newNode); // 插入后修正红黑树 return; } } else { // 插入值大于等于当前节点值 current = current.right; if (current == null) { parent.right = newNode; newNode.parent = parent; fixInsert(newNode); // 插入后修正红黑树 return; } } } } } // 修正插入后的红黑树 private void fixInsert(Node node) { Node parent, grandparent, uncle; while (node.parent != null && node.parent.isRed) { // 父节点为红色时需要修正 parent = node.parent; grandparent = parent.parent; if (parent == grandparent.left) { // 父节点为祖父节点的左子节点 uncle = grandparent.right; if (uncle != null && uncle.isRed) { // Case 1: 叔叔节点也是红色 parent.isRed = false; uncle.isRed = false; grandparent.isRed = true; node = grandparent; // 修改当前节点为祖父节点,继续往上修正 } else { if (node == parent.right) { // Case 2: 叔叔节点是黑色且当前节点是父节点的右子节点 leftRotate(parent); node = parent; parent = node.parent; // 修改当前节点为父节点,进入Case 3 } // Case 3: 叔叔节点是黑色且当前节点是父节点的左子节点 rightRotate(grandparent); parent.isRed = false; grandparent.isRed = true; node = parent.parent; // 修改当前节点为祖父节点,继续往上修正 } } else { // 父节点为祖父节点的右子节点(与父节点为左子节点的情况完全相反) uncle = grandparent.left; if (uncle != null && uncle.isRed) { // Case 4: 叔叔节点也是红色 parent.isRed = false; uncle.isRed = false; grandparent.isRed = true; node = grandparent; // 修改当前节点为祖父节点,继续往上修正 } else { if (node == parent.left) { // Case 5: 叔叔节点是黑色且当前节点是父节点的左子节点 rightRotate(parent); node = parent; parent = node.parent; // 修改当前节点为父节点,进入Case 6 } // Case 6: 叔叔节点是黑色且当前节点是父节点的右子节点 leftRotate(grandparent); parent.isRed = false; grandparent.isRed = true; node = parent.parent; // 修改当前节点为祖父节点,继续往上修正 } } } root.isRed = false; // 根节点始终为黑色 } // 左旋转 private void leftRotate(Node node) { Node rightChild = node.right; node.right = rightChild.left; if (rightChild.left != null) { rightChild.left.parent = node; } rightChild.parent = node.parent; if (node.parent == null) { root = rightChild; } else if (node == node.parent.left) { node.parent.left = rightChild; } else { node.parent.right = rightChild; } rightChild.left = node; node.parent = rightChild; } // 右旋转 private void rightRotate(Node node) { Node leftChild = node.left; node.left = leftChild.right; if (leftChild.right != null) { leftChild.right.parent = node; } leftChild.parent = node.parent; if (node.parent == null) { root = leftChild; } else if (node == node.parent.left) { node.parent.left = leftChild; } else { node.parent.right = leftChild; } leftChild.right = node; node.parent = leftChild; } } // 测试红黑树的插入操作 public class Main { public static void main(String[] args) { RedBlackTree tree = new RedBlackTree(); tree.insert(10); tree.insert(20); tree.insert(30); tree.insert(15); tree.insert(5); tree.insert(25); } } ``` 以上是一个简单的红黑树实现示例,实际上红黑树的代码实现还要考虑更多细节。使用红黑树可以实现高效地插入、删除和查找操作,这对于需要经常对数据进行插入和删除操作的场景非常有用。 ### 回答3: 红黑树(Red-Black Tree)是一种自平衡的二叉查找树。它在每个节点上增加了一个存储位来表示节点的颜色,可以为红色或黑色。通过对任何一条从根到叶子的路径上各个节点重新着色和调整树的结构,红黑树保证了在最坏情况下基本动态集合操作的时间复杂度为O(log n)。 以下是Java代码实现红黑树: ```java public class RedBlackTree<Key extends Comparable<Key>, Value> { private Node root; private static final boolean RED = true; private static final boolean BLACK = false; private class Node { private Key key; private Value value; private Node left, right; private boolean color; private int size; public Node(Key key, Value value, boolean color, int size) { this.key = key; this.value = value; this.color = color; this.size = size; } } private boolean isRed(Node node) { if (node == null) return false; return node.color == RED; } private int size(Node node) { if (node == null) return 0; return node.size; } public int size() { return size(root); } public boolean isEmpty() { return root == null; } public Value get(Key key) { if (key == null) throw new IllegalArgumentException("Key cannot be null"); return get(root, key); } private Value get(Node node, Key key) { while (node != null) { int cmp = key.compareTo(node.key); if (cmp < 0) node = node.left; else if (cmp > 0) node = node.right; else return node.value; } return null; } public boolean contains(Key key) { return get(key) != null; } public void put(Key key, Value value) { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (value == null) { delete(key); return; } root = put(root, key, value); root.color = BLACK; // root节点始终为黑色 } private Node put(Node node, Key key, Value value) { if (node == null) return new Node(key, value, RED, 1); int cmp = key.compareTo(node.key); if (cmp < 0) node.left = put(node.left, key, value); else if (cmp > 0) node.right = put(node.right, key, value); else node.value = value; if (isRed(node.right) && !isRed(node.left)) node = rotateLeft(node); if (isRed(node.left) && isRed(node.left.left)) node = rotateRight(node); if (isRed(node.left) && isRed(node.right)) flipColors(node); node.size = size(node.left) + size(node.right) + 1; return node; } private Node rotateLeft(Node node) { Node right = node.right; node.right = right.left; right.left = node; right.color = node.color; node.color = RED; right.size = node.size; node.size = size(node.left) + size(node.right) + 1; return right; } private Node rotateRight(Node node) { Node left = node.left; node.left = left.right; left.right = node; left.color = node.color; node.color = RED; left.size = node.size; node.size = size(node.left) + size(node.right) + 1; return left; } private void flipColors(Node node) { node.color = !node.color; node.left.color = !node.left.color; node.right.color = !node.right.color; } public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Tree is empty"); if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; } private Node deleteMin(Node node) { if (node.left == null) return null; if (!isRed(node.left) && !isRed(node.left.left)) node = moveRedLeft(node); node.left = deleteMin(node.left); return balance(node); } public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Tree is empty"); if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; } private Node deleteMax(Node node) { if (isRed(node.left)) node = rotateRight(node); if (node.right == null) return null; if (!isRed(node.right) && !isRed(node.right.left)) node = moveRedRight(node); node.right = deleteMax(node.right); return balance(node); } public void delete(Key key) { if (key == null) throw new IllegalArgumentException("Key cannot be null"); if (!contains(key)) return; if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; } private Node delete(Node node, Key key) { if (key.compareTo(node.key) < 0) { if (!isRed(node.left) && !isRed(node.left.left)) node = moveRedLeft(node); node.left = delete(node.left, key); } else { if (isRed(node.left)) node = rotateRight(node); if (key.compareTo(node.key) == 0 && (node.right == null)) return null; if (!isRed(node.right) && !isRed(node.right.left)) node = moveRedRight(node); if (key.compareTo(node.key) == 0) { Node min = min(node.right); node.key = min.key; node.value = min.value; node.right = deleteMin(node.right); } else { node.right = delete(node.right, key); } } return balance(node); } private Node moveRedLeft(Node node) { flipColors(node); if (isRed(node.right.left)) { node.right = rotateRight(node.right); node = rotateLeft(node); flipColors(node); } return node; } private Node moveRedRight(Node node) { flipColors(node); if (!isRed(node.left.left)) node = rotateRight(node); return node; } private Node balance(Node node) { if (isRed(node.right)) node = rotateLeft(node); if (isRed(node.left) && isRed(node.left.left)) node = rotateRight(node); if (isRed(node.left) && isRed(node.right)) flipColors(node); node.size = size(node.left) + size(node.right) + 1; return node; } public Key min() { if (isEmpty()) throw new NoSuchElementException("Tree is empty"); return min(root).key; } private Node min(Node node) { if (node.left == null) return node; return min(node.left); } public Key max() { if (isEmpty()) throw new NoSuchElementException("Tree is empty"); return max(root).key; } private Node max(Node node) { if (node.right == null) return node; return max(node.right); } public Iterable<Key> keys() { if (isEmpty()) return new LinkedList<>(); return keys(min(), max()); } public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("Low key cannot be null"); if (hi == null) throw new IllegalArgumentException("High key cannot be null"); LinkedList<Key> queue = new LinkedList<>(); keys(root, queue, lo, hi); return queue; } private void keys(Node node, LinkedList<Key> queue, Key lo, Key hi) { if (node == null) return; int cmpLo = lo.compareTo(node.key); int cmpHi = hi.compareTo(node.key); if (cmpLo < 0) keys(node.left, queue, lo, hi); if (cmpLo <= 0 && cmpHi >= 0) queue.add(node.key); if (cmpHi > 0) keys(node.right, queue, lo, hi); } } ``` 这是一个简单的Java实现红黑树的代码。每个节点包含一个键、值、颜色以及左右子节点的引用。通过一系列的旋转操作和着色调整,确保了红黑树的平衡性。代码提供了插入、删除、查找等基本操作的实现,同时还支持取最小值、最大值和范围查找等功能。

相关推荐

最新推荐

recommend-type

(001)HashMap之链表转红黑树-treefyBin方法.docx

详细解读了HashMap中链表转红黑树的treefyBin方法,该方法中涉及到的诸如:replacementTreeNode方法、treeify方法、comparableClassFor方法、compareComparables方法、tieBreakOrder方法、balanceInsertion方法、...
recommend-type

QT5开发及实例配套源代码.zip

QT5开发及实例配套[源代码],Qt是诺基亚公司的C++可视化开发平台,本书以Qt 5作为平台,每个章节在简单介绍开发环境的基础上,用一个小实例,介绍Qt 5应用程序开发各个方面,然后系统介绍Qt 5应用程序的开发技术,一般均通过实例介绍和讲解内容。最后通过三个大实例,系统介绍Qt 5综合应用开发。光盘中包含本书教学课件和书中所有实例源代码及其相关文件。通过学习本书,结合实例上机练习,一般能够在比较短的时间内掌握Qt 5应用技术。本书既可作为Qt 5的学习和参考用书,也可作为大学教材或Qt 5培训用书。
recommend-type

grpcio-1.46.3-cp37-cp37m-musllinux_1_1_i686.whl

Python库是一组预先编写的代码模块,旨在帮助开发者实现特定的编程任务,无需从零开始编写代码。这些库可以包括各种功能,如数学运算、文件操作、数据分析和网络编程等。Python社区提供了大量的第三方库,如NumPy、Pandas和Requests,极大地丰富了Python的应用领域,从数据科学到Web开发。Python库的丰富性是Python成为最受欢迎的编程语言之一的关键原因之一。这些库不仅为初学者提供了快速入门的途径,而且为经验丰富的开发者提供了强大的工具,以高效率、高质量地完成复杂任务。例如,Matplotlib和Seaborn库在数据可视化领域内非常受欢迎,它们提供了广泛的工具和技术,可以创建高度定制化的图表和图形,帮助数据科学家和分析师在数据探索和结果展示中更有效地传达信息。
recommend-type

大学生毕业答辨ppt免费模板【不要积分】下载可编辑可用(138).zip

大学生毕业答辨ppt免费模板【不要积分】下载可编辑可用(138).zip
recommend-type

Eclipse的C/C++自动补全插件org.eclipse.cdt.ui-7.3.100.202111091601

Eclipse的C/C++自动补全插件,制作参考:https://blog.csdn.net/kingfox/article/details/104121203?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-1-104121203-blog-117118786.235%5Ev43%5Epc_blog_bottom_relevance_base1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2~default~BlogCommendFromBaidu~Rate-1-104121203-blog-117118786.235%5Ev43%5Epc_blog_bottom_relevance_base1&utm_relevant_index=2
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

用Spring boot和vue写一个登录注册界面

好的,这是一个比较常见的技术问题,我可以为您提供一些参考资料和思路。首先,您可以使用Spring Boot作为后端框架来处理用户认证和注册的逻辑,比如使用Spring Security实现用户登录认证。同时,您还需要设计相应的数据模型和数据库表结构来存储用户信息。在前端方面,您可以使用Vue.js作为框架来构建登录注册页面,使用Axios来发起API请求并和后端进行交互。当然,在实现过程中,还需要考虑一些具体细节,比如数据校验、安全性和用户体验等方面。希望这些信息能够帮助到您。
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。