getVerticalPathBetweenNodes method

  1. @override
Set<Node> getVerticalPathBetweenNodes(
  1. Node first,
  2. Node second, {
  3. Map<String, int>? depths,
})
override

Returns the path between two vertices within a subtree.

Determines which vertex is higher. Then moves up the graph until reaching the parent vertex.

If during the process the parent vertex is not found (for example, the root has no parents), it stops and returns an empty path.

Pre-calculated depths of vertices can be passed. If pre-calculated depths are not passed, the depth for each vertex is computed.

Implementation

@override
Set<Node> getVerticalPathBetweenNodes(
  Node first,
  Node second, {
  Map<String, int>? depths,
}) {
  late final Node parent;
  late final Node child;

  final firstDepth = depths?[first.key] ?? getNodeLevel(first);
  final secondDepth = depths?[second.key] ?? getNodeLevel(second);

  if (firstDepth < secondDepth) {
    parent = first;
    child = second;
  } else {
    parent = second;
    child = first;
  }

  Node current = child;
  final List<Node> path = [current];

  while (current != parent) {
    final tempParent = getNodeParent(current);
    if (tempParent != null) {
      path.insert(0, tempParent);
      current = tempParent;
    } else {
      path.clear();
      break;
    }
  }

  return path.toSet();
}