@@ -465,54 +465,61 @@ protected bool _remove(RedBlackTreeNode<TKey> nodeToDelete)
465
465
return false ;
466
466
}
467
467
468
- // X it's node that will become move to original nodeToDelete position in the tree.
469
- RedBlackTreeNode < TKey > x ;
470
-
471
- if ( nodeToDelete . HasOnlyRightChild )
472
- {
473
- x = nodeToDelete . RightChild ;
474
- Transplant ( nodeToDelete , nodeToDelete . RightChild ) ;
475
- }
476
- else if ( nodeToDelete . HasOnlyLeftChild )
468
+ if ( ! nodeToDelete . HasChildren )
477
469
{
478
- x = nodeToDelete . LeftChild ;
479
- Transplant ( nodeToDelete , nodeToDelete . LeftChild ) ;
470
+ Root = null ;
480
471
}
481
472
else
482
473
{
483
- // Y it's node that will become move to original X position in the tree.
484
- var y = ( RedBlackTreeNode < TKey > ) _findMinNode ( nodeToDelete . RightChild ) ;
485
- x = y . RightChild ;
474
+ // X it's node that will become move to original nodeToDelete position in the tree.
475
+ RedBlackTreeNode < TKey > x ;
486
476
487
- if ( y . Parent == nodeToDelete )
477
+ if ( nodeToDelete . HasOnlyRightChild )
488
478
{
489
- if ( x != null )
490
- {
491
- x . Parent = y ;
492
- }
479
+ x = nodeToDelete . RightChild ;
480
+ Transplant ( nodeToDelete , nodeToDelete . RightChild ) ;
493
481
}
494
- else
482
+ else if ( nodeToDelete . HasOnlyLeftChild )
495
483
{
496
- Transplant ( y , y . RightChild ) ;
497
- y . RightChild = nodeToDelete . RightChild ;
498
- y . RightChild . Parent = y ;
484
+ x = nodeToDelete . LeftChild ;
485
+ Transplant ( nodeToDelete , nodeToDelete . LeftChild ) ;
499
486
}
487
+ else
488
+ {
489
+ // Y it's node that will become move to original X position in the tree.
490
+ var y = ( RedBlackTreeNode < TKey > ) _findMinNode ( nodeToDelete . RightChild ) ;
491
+ x = y . RightChild ;
500
492
501
- Transplant ( nodeToDelete , y ) ;
502
- y . LeftChild = nodeToDelete . LeftChild ;
503
- y . LeftChild . Parent = y ;
504
- y . Color = nodeToDelete . Color ;
493
+ if ( y . Parent == nodeToDelete )
494
+ {
495
+ if ( x != null )
496
+ {
497
+ x . Parent = y ;
498
+ }
499
+ }
500
+ else
501
+ {
502
+ Transplant ( y , y . RightChild ) ;
503
+ y . RightChild = nodeToDelete . RightChild ;
504
+ y . RightChild . Parent = y ;
505
+ }
505
506
506
- if ( Root == nodeToDelete )
507
- {
508
- Root = y ;
509
- Root . Parent = null ;
507
+ Transplant ( nodeToDelete , y ) ;
508
+ y . LeftChild = nodeToDelete . LeftChild ;
509
+ y . LeftChild . Parent = y ;
510
+ y . Color = nodeToDelete . Color ;
511
+
512
+ if ( Root == nodeToDelete )
513
+ {
514
+ Root = y ;
515
+ Root . Parent = null ;
516
+ }
510
517
}
511
- }
512
518
513
- if ( nodeToDelete . Color == RedBlackTreeColors . Black )
514
- {
515
- _adjustTreeAfterRemoval ( x ) ;
519
+ if ( nodeToDelete . Color == RedBlackTreeColors . Black )
520
+ {
521
+ _adjustTreeAfterRemoval ( x ) ;
522
+ }
516
523
}
517
524
518
525
base . _count -- ;
0 commit comments