Check if a given tree graph is linear or not

Given a tree check if it is linear or not.

    1
  /    \
 2      3
 Linear as we can
 form a lime 2 1 3
    1
  /    \
 2      3
      /   \
     4     5
Not linear

Examples:

Input : 3
1 2
1 3
Output :
YES
Explanation:
The Tree formed is 2-1-3 which is a linear one.

Input :
4
1 2
2 3
4 2
Output :
NO

Approach:The given tree would be linear only if n-2 of its nodes have indegree == 2 or number of nodes, n==1.



filter_none

edit
close

play_arrow

link
brightness_4
code

// A Java Program to check whether a graph is 
// Linear or not
import java.io.*;
import java.util.*;
  
// This class represents a undirected graph 
// using adjacency list representation
class Graph {
    private int V; // No. of vertices
  
    // Adjacency List
    private LinkedList<Integer> adj[];
  
    // Constructor
    Graph(int v)
    {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new LinkedList<Integer>();
    }
  
    // Function to add an edge into the graph
    void addEdge(int v, int w)
    {
        adj[v].add(w);
        adj[w].add(v);
    }
  
    // Returns true if the graph is linear, 
    // else false.
    boolean isLinear()
    {
        // If the number of vertice is 1 then
        // the tree is always Linear
        if (V == 1)
            return true;
        int count = 0;
  
        // Counting the number of vertices
        // with indegree 2
        for (int i = 0; i < V; i++) {
            if (adj[i].size() == 2)
                count++;
        }
        if (count == V - 2)
            return true;
        else
            return false;
    }
  
    // Driver method
    public static void main(String args[])
    {
        // Create a graph given in the above example
        Graph g1 = new Graph(3);
        g1.addEdge(0, 1);
        g1.addEdge(0, 2);
        if (g1.isLinear())
            System.out.println("YES");
        else
            System.out.println("NO");
    }
}

chevron_right


Output :

YES


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.