Skip to content

Commit

Permalink
isLeaf, hasChildren
Browse files Browse the repository at this point in the history
  • Loading branch information
leo-lox committed Nov 2, 2024
1 parent 3f5332f commit 249bb35
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions lib/domain_layer/entities/tree_node.dart
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
class TreeNode<T> {
T value;
final T value;
TreeNode<T>? parent;
List<TreeNode<T>> children;
final List<TreeNode<T>> _children;

bool get isFirstChild => parent?.children.first == this;
bool get isLastChild => parent?.children.last == this;
bool get hasSiblings => parent != null && parent!.children.length > 1;

TreeNode(this.value) : children = <TreeNode<T>>[];
bool get hasChildren => _children.isNotEmpty;
bool get isLeaf => _children.isEmpty;
List<TreeNode<T>> get children => List.unmodifiable(_children);

TreeNode(this.value) : _children = <TreeNode<T>>[];

void addChild(TreeNode<T> child) {
children.add(child);
_children.add(child);
child.parent = this;
}

void addChildren(List<TreeNode<T>> children) {
for (var child in children) {
addChild(child);
}
}

void removeChild(TreeNode<T> child) {
_children.remove(child);
child.parent = null;
}

void printTree([String prefix = '']) {
print('$prefix${value.toString()}');
for (var i = 0; i < children.length; i++) {
var child = children[i];
var isLastChild = i == children.length - 1;
for (var i = 0; i < _children.length; i++) {
var child = _children[i];
var isLastChild = i == _children.length - 1;
child.printTree('$prefix${isLastChild ? '└── ' : '├── '}');
}
}
Expand Down

0 comments on commit 249bb35

Please sign in to comment.