
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a given tree graph is linear or not in C++
Here we will see how to check whether a tree graph is linear or not. A linear tree graph can be expressed in one line, suppose this is an example of a linear tree graph.
But this is not linear −
To check a graph is linear or not, we can follow two conditions
- If the number of nodes is 1, then the tree graph is linear
- If (n – 2) of its nodes have in-degree 2
Example
#include <iostream> #include <vector> #define N 4 using namespace std; class Graph{ private: int V; vector<int> *adj; public: Graph(int v){ V = v; adj = new vector<int>[v]; } void addEdge(int u, int v){ adj[u].push_back(v); adj[v].push_back(u); } bool isLinear() { if (V == 1) return true; int count = 0; for (int i = 0; i < V; i++) { if (adj[i].size() == 2) count++; } if (count == V - 2) return true; else return false; } }; int main() { Graph g1(3); g1.addEdge(0, 1); g1.addEdge(0, 2); if (g1.isLinear()) cout << "The graph is linear"; else cout << "The graph is not linear"; }
Output
The graph is linear
- Related Articles
- Check if a given graph is tree or not
- C++ Program to Check if a Directed Graph is a Tree or Not Using DFS
- C++ program to Check if a Given Binary Tree is an AVL Tree or Not
- C++ Program to Check if an UnDirected Graph is a Tree or Not Using DFS
- Check if a Tree is Isomorphic or not in C++
- Check if a directed graph is connected or not in C++
- Program to check whether given tree is symmetric tree or not in Python
- Check if a binary tree is sorted levelwise or not in C++
- Check whether given degrees of vertices represent a Graph or Tree in Python
- Program to check whether given graph is bipartite or not in Python
- C++ Program to Check Whether a given Binary Tree is a Full Binary Tree or not
- Program to check given graph is a set of trees or not in Python
- Check if a binary tree is sorted level-wise or not in C++
- C++ Program to Check if a Given Graph must Contain Hamiltonian Cycle or Not\n
- Check if a given matrix is sparse or not in C++

Advertisements