VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-if-a-given-tree-graph-is-linear-or-not/

⇱ Check if a given tree graph is linear or not - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Check if a given tree graph is linear or not

Last Updated : 7 Sep, 2022

Given a tree check if it is linear or not.

 1
 / \
 2 3
 Linear as we can
 form a line 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.  

Implementation:


Output
YES
Comment
Article Tags: