@@ -1397,6 +1397,73 @@ func TestRBTree_KeyValues(t *testing.T) {
13971397 }
13981398}
13991399
1400+ func TestRBTree_Iterate (t * testing.T ) {
1401+ for _ , testCase := range []struct {
1402+ name string
1403+ expectedLen int
1404+ inputStart int
1405+ inputEnd int
1406+ // 如果为true则遍历结束
1407+ endConditionFunc func (key int ) bool
1408+ }{
1409+ {
1410+ name : "treeMap为空" ,
1411+ expectedLen : 0 ,
1412+ inputStart : 1 ,
1413+ inputEnd : 0 ,
1414+ endConditionFunc : func (key int ) bool {
1415+ return false
1416+ },
1417+ },
1418+ {
1419+ name : "treeMap 有10000个元素,遍历所有小于等于8000的元素" ,
1420+ expectedLen : 8000 ,
1421+ inputStart : 1 ,
1422+ inputEnd : 10000 ,
1423+ endConditionFunc : func (key int ) bool {
1424+ return key > 8000
1425+ },
1426+ },
1427+ {
1428+ name : "treeMap 有10000个元素,遍历所有元素" ,
1429+ expectedLen : 10000 ,
1430+ inputStart : 1 ,
1431+ inputEnd : 10000 ,
1432+ endConditionFunc : func (key int ) bool {
1433+ return false
1434+ },
1435+ },
1436+ {
1437+ name : "treeMap 有10个元素,由于第一个就不符合条件所以遍历立刻中断" ,
1438+ expectedLen : 0 ,
1439+ inputStart : 1 ,
1440+ inputEnd : 10 ,
1441+ endConditionFunc : func (key int ) bool {
1442+ return key < 5
1443+ },
1444+ },
1445+ } {
1446+ t .Run (testCase .name , func (t * testing.T ) {
1447+ rbTree := NewRBTree [int , int ](compare ())
1448+ for i := testCase .inputStart ; i <= testCase .inputEnd ; i ++ {
1449+ assert .Nil (t , rbTree .Add (i , i ))
1450+ }
1451+ arr := make ([]int , 0 )
1452+ rbTree .Iterate (func (key , value int ) bool {
1453+ if testCase .endConditionFunc (key ) {
1454+ return false
1455+ }
1456+ arr = append (arr , value )
1457+ return true
1458+ })
1459+ assert .Equal (t , testCase .expectedLen , len (arr ))
1460+ for i := 0 ; i < testCase .expectedLen ; i ++ {
1461+ assert .Equal (t , testCase .inputStart + i , arr [i ])
1462+ }
1463+ })
1464+ }
1465+ }
1466+
14001467// IsRedBlackTree 检测是否满足红黑树
14011468func IsRedBlackTree [K any , V any ](root * rbNode [K , V ]) bool {
14021469 // 检测节点是否黑色
0 commit comments