Skip to content

Conversation

@happy-san
Copy link
Collaborator

@happy-san happy-san commented Dec 19, 2020

I'm working on AvlTree, I've migrated it to nnbd but I'm updating comments.
#35

Move trees and tests to nnbd.
@happy-san happy-san marked this pull request as draft December 19, 2020 12:37
///
/// In [AvlTree] it is the primary focus to actively balance out all
/// imbalanced [node]s following addition or deletion.
int balanceFactor = 0;
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about using a Map here? Combines the good of both enum and current definition
'rightHeavy' -> -1
'balanced' -> 0
'leftHeavy' -> 1

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, I like this implementation

enum BalanceState { rightHeavy, balanced, leftHeavy }

class Node {
  BalanceState balanceState = BalanceState.balanced;

  int get balanceFactor {
    switch (balanceState) {
      case BalanceState.rightHeavy:
        return -1;
      case BalanceState.balanced:
        return 0;
      case BalanceState.leftHeavy:
        return 1;
    }
  }
}

void main() {
  var node = Node();

  print(node.balanceState);
  print(node.balanceFactor);
}

This prints

BalanceState.balanced
0

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It just occured to me, if a node is leftHeavy, it's balance factor can be any natural number. Similarly rightHeavy node's balance factor can be any negative integer. So by definition, it cannot be hardcoded, like I did.

Comment on lines 458 to 471
// [node] was balanced before deletion. (Both left and right subtree had
// the same height.)
// N
// / \
// ** **
case 0:
// node is right heavy now.
// [node] is right heavy now.
// N
// / \
// * **
node.balanceFactor = -1;
_isShorter = false;
break;

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@code-shoily Do you think the added comment helps or it's just cluttering?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No it does help.

@happy-san happy-san marked this pull request as ready for review January 17, 2021 14:46
@happy-san happy-san merged commit 0d1b947 into code-shoily:master Jan 17, 2021
@happy-san happy-san deleted the nnbd branch January 17, 2021 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants