Topological sort/union find, verify all nodes converge to a single root and no cycle? bool isTree(vector nodes) { if (nodes.size() == 0) return true; TreeNode * root = getRoot(nodes[0]); if (root == NULL) return false; for (int i = 1; i < nodes.size(); ++ i) { if (getRoot(nodes[i]) != root) return false; } return true; } // getParent(n): return NULL if no parent TreeNode * getRoot(TreeNode * n) { unordered_set s; for (TreeNode * p = getParent(n); p != NULL; p = getParent(n)) { if (s.find(n) != s.end()) return NULL; // cycle found s.insert(n); n = p; } return n; }