diff --git a/include/higra/structure/tree_graph.hpp b/include/higra/structure/tree_graph.hpp index c5867f60..6a6a7f0a 100644 --- a/include/higra/structure/tree_graph.hpp +++ b/include/higra/structure/tree_graph.hpp @@ -255,6 +255,12 @@ namespace hg { private: void _init() { + if (_parents.size() == 0) { + _root = invalid_index; + _num_vertices = 0; + _num_leaves = 0; + return; + } hg_assert(_parents.shape().size() == 1, "parents must be a linear (1d) array"); _num_vertices = _parents.size(); _root = _num_vertices - 1; diff --git a/test/cpp/structure/test_tree.cpp b/test/cpp/structure/test_tree.cpp index 8f76c43a..9cd11555 100644 --- a/test/cpp/structure/test_tree.cpp +++ b/test/cpp/structure/test_tree.cpp @@ -32,6 +32,10 @@ namespace tree { hg::tree t1; REQUIRE(hg::num_vertices(t1) == 0); + array_1d p1{}; + hg::tree t11(p1); + REQUIRE(hg::num_vertices(t11) == 0); + array_1d p2{5, 5, 6, 6, 6, 7, 7, 7}; hg::tree t2(p2); REQUIRE(hg::num_vertices(t2) == 8); diff --git a/test/python/test_structure/test_tree.py b/test/python/test_structure/test_tree.py index acf282d5..d69de1a0 100644 --- a/test/python/test_structure/test_tree.py +++ b/test/python/test_structure/test_tree.py @@ -40,6 +40,15 @@ def test_size_tree(self): self.assertTrue(t.parent(4) == 6) self.assertTrue(np.all(t.parent((0, 5, 2, 3, 7)) == (5, 7, 6, 6, 7))) + def test_empty_tree(self): + t = hg.Tree([]) + + self.assertTrue(t.category() == hg.TreeCategory.PartitionTree) + self.assertTrue(t.root() == -1) + self.assertTrue(t.num_vertices() == 0) + self.assertTrue(t.num_edges() == 0) + self.assertTrue(t.num_leaves() == 0) + def test_dynamic_attributes(self): t = TestTree.get_tree() t.new_attribute = 42