Is the Graph a Tree

mediumcodingAlgorithmsGraphs

Overview

Given n nodes labeled from 0 to n - 1 and a list of undirected edges, determine if these edges form a valid tree.

A valid tree must satisfy:

  1. It is connected — all nodes are reachable from any node.
  2. It has no cycles.

An equivalent check: a graph with n nodes is a tree if and only if it is connected and has exactly n - 1 edges.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • edges[i].length === 2
  • 0 <= edges[i][0], edges[i][1] < n
  • No duplicate edges.

Examples

isTree(5, [[0,1], [0,2], [0,3], [1,4]]);
// => true
//    0
//   /|\
//  1 2 3
//  |
//  4
isTree(5, [[0,1], [1,2], [2,3], [1,3], [1,4]]);
// => false  (cycle: 1-2-3-1)

isTree(4, [[0,1], [2,3]]);
// => false  (not connected)

Solution

Reveal solution
function isTree(n, edges) {
  if (edges.length !== n - 1) return false;

  const parent = Array.from({ length: n }, (_, i) => i);

  function find(x) {
    while (parent[x] !== x) {
      parent[x] = parent[parent[x]];
      x = parent[x];
    }
    return x;
  }

  for (const [a, b] of edges) {
    const rootA = find(a), rootB = find(b);
    if (rootA === rootB) return false; // cycle detected
    parent[rootA] = rootB;
  }

  return true;
}

A tree with n nodes has exactly n - 1 edges. If we also verify no cycle exists via Union-Find, the graph must be a connected tree.

Resources

NameTopicDifficulty
Add BinaryAlgorithmseasyBalanced Binary TreeAlgorithmseasyBalanced BracketsAlgorithmseasyBinary SearchAlgorithmseasyBinary Search Tree Lowest Common AncestorAlgorithmseasyBinary Tree Maximum DepthAlgorithmseasyBinary Tree SubtreeAlgorithmseasyBit CountingAlgorithmseasyBit ReversalAlgorithmseasyCount Set Bits in a Binary NumberAlgorithmseasyDiameter of Binary TreeAlgorithmseasyFind Duplicates in ArrayAlgorithmseasyFirst Bad VersionAlgorithmseasyFlip Binary TreeAlgorithmseasyFlood FillAlgorithmseasyLinked List Detect CycleAlgorithmseasyLinked List ReversalAlgorithmseasyLinked Lists Combine Two SortedAlgorithmseasyLongest PalindromeAlgorithmseasyMiddle of the Linked ListAlgorithmseasyMost Common ElementsAlgorithmseasyOptimal Stock TradingAlgorithmseasyPair SumAlgorithmseasyRansom NoteAlgorithmseasyStaircase Climbing CombinationsAlgorithmseasyString AnagramAlgorithmseasyString PalindromeAlgorithmseasy01 MatrixAlgorithmsmediumAccounts MergeAlgorithmsmediumArray Product Excluding CurrentAlgorithmsmediumBinary Search Tree Kth Smallest ElementAlgorithmsmediumBinary Tree Level Order TraversalAlgorithmsmediumBinary Tree Rebuilding from Preorder and Inorder TraversalsAlgorithmsmediumBinary Tree Right Side ViewAlgorithmsmediumCombinations for Target SumAlgorithmsmediumCount Islands in a GridAlgorithmsmediumCourse DependencyAlgorithmsmediumDecode MessageAlgorithmsmediumDisjoint IntervalsAlgorithmsmediumDistinct Paths in GridAlgorithmsmediumEvaluate Reverse Polish NotationAlgorithmsmediumFind All Anagrams in a StringAlgorithmsmediumFind Element in Rotated ArrayAlgorithmsmediumFind the Longest Palindromic SubstringAlgorithmsmediumFind Word in GridAlgorithmsmediumGraph CloneAlgorithmsmediumGraph Count Connected ComponentsAlgorithmsmediumIs the Graph a TreeAlgorithmsmediumK Closest Points to OriginAlgorithmsmediumLetter Combinations of a Phone NumberAlgorithmsmediumLongest Increasing SubsequenceAlgorithmsmediumLongest Non-repeating SubstringAlgorithmsmediumLongest Repeating Substring After ReplacementsAlgorithmsmediumLowest Common Ancestor of a Binary TreeAlgorithmsmediumMatrix RotationAlgorithmsmediumMatrix Spiral TraversalAlgorithmsmediumMatrix ZeroingAlgorithmsmediumMaximum Sum in Contiguous ArrayAlgorithmsmediumMaximum Water Trapped Between WallsAlgorithmsmediumMerge New IntervalAlgorithmsmediumMerge Overlapping IntervalsAlgorithmsmediumMinimum Coins for ChangeAlgorithmsmediumMinimum Height TreesAlgorithmsmediumPalindromic SubstringsAlgorithmsmediumPartition Equal Subset SumAlgorithmsmediumPermutationsAlgorithmsmediumRotting OrangesAlgorithmsmediumSegment WordsAlgorithmsmediumSort ColorsAlgorithmsmediumString Anagram GroupsAlgorithmsmediumString to Integer (atoi)AlgorithmsmediumSubsetsAlgorithmsmediumSum Without AdditionAlgorithmsmediumTask CoordinationAlgorithmsmediumTrie (Prefix Tree)AlgorithmsmediumTriplet SumAlgorithmsmediumValidate Binary Search TreeAlgorithmsmediumBasic CalculatorAlgorithmshardBinary Tree EqualAlgorithmshardBinary Tree Maximum Total PathAlgorithmshardDelete Nth Node from End of Linked ListAlgorithmshardEnd of Array ReachableAlgorithmshardExtraterrestrial LanguageAlgorithmshardFind Missing Number in SequenceAlgorithmshardFind Words in GridAlgorithmshardLargest Rectangle in HistogramAlgorithmshardLinked Lists Combine K SortedAlgorithmshardLongest Common SubsequenceAlgorithmshardLongest Consecutive Number SequenceAlgorithmshardMaximum Product in Contiguous ArrayAlgorithmshardMaximum Profit in Job SchedulingAlgorithmshardMeeting CalendarAlgorithmshardMinimum Meeting Rooms NeededAlgorithmshardNeighborhood TheftAlgorithmshardNeighborhood Theft (Circular)AlgorithmshardNumber Stream MedianAlgorithmshardOcean FlowAlgorithmshardRearrange Linked ListAlgorithmshardShortest Substring Containing CharactersAlgorithmshardSmallest Element in Rotated Sorted ArrayAlgorithmshardTrapping Rain WaterAlgorithmshardWord FinderAlgorithmshardWord LadderAlgorithmshard
103 of 103 problems