Here's another approach:
class NodesByZIndex:
var nodes: Array = []
func get_nodes(z: int, root: Node) -> void:
if root is Node2D and root.z_index == z:
nodes.append(root)
for child in root.get_children():
get_nodes(z, child)
# Test NodesByZIndex.
var nbzi = NodesByZIndex.new()
nbzi.get_nodes(0, $"/root")
print("Nodes with z_index 0:")
for node in nbzi.nodes:
prints(node, node.name, node.z_index)