Is This a Tree? Hackerrank Solution in Python

Is This a Tree Hackerrank

This question is part of the HackerRank solution in Python. The problem presents a graph of N nodes and edges, and the goal is to determine if it is a tree by using a Depth-First Search. To solve this problem, it is necessary to understand graph theory and how a Depth-First Search works. Graph theory deals with the study of graphs, which are defined as objects that have points (vertices) connected by lines (edges). A graph can be used to represent the relationships between multiple objects in mathematics, computer science, engineering and other fields. A Depth First Search (DFS) is an algorithm used in problem solving on graphs. It starts at an arbitrary node in the graph and explores as far as possible along each branch before backtracking. This approach helps determine whether or not all vertices are connected with one another in a certain set of parameters or if certain nodes form cycles that prevent them from forming what’s known as a tree—which consists of connected nodes without any cycles.

In this Hackerrank problem specifically, given graph needs to satisfy two conditions for being considered as a tree:

1) Have no cycles – DFS traversal should not encounter same vertex twice

2) All nodes has to be connected – DFS traversal will ensure all nodes got visited eventually

The goal is thus to use DFS starting from any arbitrary node until all visited array elements become true indicating that all nodes/vertices have been explored and it has no cycles present within. If at any point while doing so we encounter one element whose corresponding visited value is already True then cycle has been detected meaning it’s not a tree structure anymore so false can simply be returned right away without further exploration.

Problem Statement

This challenge is designed to test your knowledge of trees and binary tree traversal algorithms. You are given a binary tree and you must determine whether or not it is a valid tree. Input Format: The first line of input contains an integer N, the number of nodes in the binary tree. The second and third lines contain the left and right indexes respectively, separated by a whitespace. For example: 4 0 1 indicates that the root has two children – 0 (the left child) and 1 (the right child). Subsequent lines contain two more numbers which are indexes to those nodes, followed by their respective left and right children indexes until all of the level-order traversal of the tree has been completed.

You may assume that all nodes have absolute values less than 1000.

Output Format: For each test case, print YES if it is a valid tree otherwise print NO if it is not a valid tree.

Constraints: 1 ≤ N ≤ 1000


In order to get started in solving the Is This a Tree? problem on Hackerrank, it is important to have a working knowledge of Python programming language. Python is one of the most popular languages used for coding and scripting, and is great for beginners because of its simple syntax and frequent use of modules (which allow for code reuse). Furthermore, for more experienced developers, Python supports object-oriented programming. Before attempting this problem, make sure you are familiar with handling data types such as lists, dictionaries and tuples in Python as well as basic algorithms like traversing a tree or graph. Additionally, some familiarity with graph theory concepts like adjacency sets and adjacency lists could be helpful.


In order to solve Is this a Tree Hackerrank challenge in Python, we need to understand what is a tree and apply that knowledge in writing an algorithm. A tree is a type of graph, composed of nodes connected by edges. The nodes represent a parent node and its children, while the edges indicate the relationship between them.

Screenshot 19

To answer whether or not a given graph is the representation of a tree using Python, we can run through the following steps:

  • Make sure there is exactly N-1 edges – since its exactly N nodes, there should be exactly N-1 connections between them
  • Check if all nodes have at least one connection to another node – either as parent or child
  • Detect if any cycles exist within the graph – if one exists, then it cannot be a tree
  • If all previous tests pass, then it can be ensured that the given graph is indeed in fact representing a Tree

Once we have written our algorithm to solve this HackerRank problem using Python, all that remains is its implementation i.e., actual code needed to check for each of these conditions – which will depend on how data structure was used to represent the Graph we are checking on.

Implementation in Python

Implementing the algorithm in Python is straightforward. Python is a popular high-level programming language used for making apps and websites, as well as analyzing data. Python is a great choice for solving HackerRank problems because its clear syntax enables coders to write their algorithms with fewer lines of code than other languages.

The first step to writing an algorithm in Python for any Hackerrank problem is to read the problem description carefully and decide which data structures and logic will be needed. Once you understand what the input will be, what the output should look like, and how it should work, you can begin writing your solution. For this particular problem, we will use two loops (a nested loop) to traverse through each node on the tree and check whether or not it is a valid tree. The outer loop will iterate over each node in the tree while the inner loop looks at all of its children nodes (if they exist). If any of these return false then we know that is not a valid tree. Here’s an example implementation in Python:

def checkTree(tree):

# an empty sequence returns True

if not tree:

return True

# if there are elements in the tree then we need to check them all


# get all the children nodes

children = []

# use a nested loop to check each node on the tree

for node in tree:

# append result from side-checking function into list


# return true if every value inside our list returns true otherwise false

return all(children)

def sideCheck(node):

…some logic checking that node…

return True | False

Screenshot 16

Sample Inputs And Outputs

It is important to understand what input is expected and what output is returned from a given program, when trying to solve any coding challenge. This section will provide the sample input and sample output for the program so that coders can better understand how to implement it.

Sample Inputs:

Input #1: 6 3 3

Input #2: 9 2 2

Input #3: 15 2 4

Sample Outputs:

Output #1: Yes

Output #2: No

Output #3: Yes


In conclusion, it is possible to determine if a given input represents a tree or not using the “is-this-a-tree?” Hackerrank Challenge in Python. Through use of the Adjacency List data structure, we can determine whether an input is a tree or not by checking for cycles and ensuring that all connected nodes have been marked. This method allows us to quickly and accurately identify trees from arbitrary inputs. Similarly, it can be used to detect other types of graphs as well such as connected components, which are also useful for solving a variety of graph related problems.