इस समस्या में, एक अप्रत्यक्ष ग्राफ दिया गया है, हमें यह जांचना है कि ग्राफ पेड़ है या नहीं। हम इसे केवल एक पेड़ के मानदंड की जाँच करके पा सकते हैं। एक पेड़ में एक चक्र नहीं होगा, इसलिए यदि ग्राफ में कोई चक्र है, तो वह पेड़ नहीं है।

हम इसे दूसरे दृष्टिकोण का उपयोग करके देख सकते हैं, यदि ग्राफ जुड़ा हुआ है और इसमें V-1 किनारे हैं, तो यह एक पेड़ हो सकता है। यहाँ V ग्राफ में शीर्षों की संख्या है।
इनपुट और आउटपुट
Input: The adjacency matrix. 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 1 1 1 1 0 Output: The Graph is a tree
एल्गोरिदम
isCycle(u, विज़िट किया गया, पैरेंट)
इनपुट: प्रारंभ शीर्ष u, विज़िट की गई सूची जिसे विज़िट किया गया है या नहीं, मूल शीर्ष को चिह्नित करने के लिए।
आउटपुट: सही है अगर ग्राफ़ में कोई चक्र है।
Begin mark u as visited for all vertex v which are adjacent with u, do if v is visited, then if isCycle(v, visited, u) = true, then return true else if v ≠ parent, then return true done return false End
isTree(ग्राफ)
इनपुट: अप्रत्यक्ष ग्राफ।
आउटपुट: सही है जब ग्राफ़ एक पेड़ है।
Begin define a visited array to mark which node is visited or not initially mark all node as unvisited if isCycle(0, visited, φ) is true, then //the parent of starting vertex is null return false if the graph is not connected, then return false return true otherwise End
उदाहरण
#include<iostream>
#define NODE 5
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 1, 1, 0},
{1, 0, 1, 0, 0},
{1, 1, 0, 0, 0},
{1, 0, 0, 0, 1},
{0, 0, 0, 1, 0}
};
bool isCycle(int u, bool visited[], int parent) {
visited[u] = true; //mark v as visited
for(int v = 0; v<NODE; v++) {
if(graph[u][v]) {
if(!visited[v]) { //when the adjacent node v is not visited
if(isCycle(v, visited, u)) {
return true;
}
} else if(v != parent) { //when adjacent vertex is visited but not parent
return true; //there is a cycle
}
}
}
return false;
}
bool isTree() {
bool *vis = new bool[NODE];
for(int i = 0; i<NODE; i++)
vis[i] = false; //initialize as no node is visited
if(isCycle(0, vis, -1)) //check if there is a cycle or not
return false;
for(int i = 0; i<NODE; i++) {
if(!vis[i]) //if there is a node, not visited by traversal, graph is not connected
return false;
}
return true;
}
int main() {
if(isTree())
cout << "The Graph is a Tree.";
else
cout << "The Graph is not a Tree.";
} आउटपुट
The Graph is a Tree.