------------------------------------------------------------------------------
| 98 | |
| 99 | //------------------------------------------------------------------------------ |
| 100 | bool vtkTree::IsStructureValid(vtkGraph* g) |
| 101 | { |
| 102 | if (!g) |
| 103 | { |
| 104 | return false; |
| 105 | } |
| 106 | |
| 107 | vtkTree* tree = vtkTree::SafeDownCast(g); |
| 108 | if (tree) |
| 109 | { |
| 110 | // Since a tree has the additional root property, we need |
| 111 | // to set that here. |
| 112 | this->Root = tree->Root; |
| 113 | return true; |
| 114 | } |
| 115 | |
| 116 | // Empty graph is a valid tree. |
| 117 | if (g->GetNumberOfVertices() == 0) |
| 118 | { |
| 119 | this->Root = -1; |
| 120 | return true; |
| 121 | } |
| 122 | |
| 123 | // A tree must have one more vertex than its number of edges. |
| 124 | if (g->GetNumberOfEdges() != g->GetNumberOfVertices() - 1) |
| 125 | { |
| 126 | return false; |
| 127 | } |
| 128 | |
| 129 | // Find the root and fail if there is more than one. |
| 130 | vtkIdType root = -1; |
| 131 | for (vtkIdType v = 0; v < g->GetNumberOfVertices(); ++v) |
| 132 | { |
| 133 | vtkIdType indeg = g->GetInDegree(v); |
| 134 | if (indeg > 1) |
| 135 | { |
| 136 | // No tree vertex should have in degree > 1, so fail. |
| 137 | return false; |
| 138 | } |
| 139 | else if (indeg == 0 && root == -1) |
| 140 | { |
| 141 | // We found our first root. |
| 142 | root = v; |
| 143 | } |
| 144 | else if (indeg == 0) |
| 145 | { |
| 146 | // We already found a root, so fail. |
| 147 | return false; |
| 148 | } |
| 149 | } |
| 150 | if (root < 0) |
| 151 | { |
| 152 | return false; |
| 153 | } |
| 154 | |
| 155 | // Make sure the tree is connected with no cycles. |
| 156 | std::vector<bool> visited(g->GetNumberOfVertices(), false); |
| 157 | std::vector<vtkIdType> stack; |
no test coverage detected