HARD NC#91 Blind #33 Graphs / Trees
261. Graph Valid Tree
📖 Problem
Given the number of nodes n and a list of n - 1 edges where edges[i] = [ai, bi] indicates that there is an edge between node ai and node bi in the tree, return true if and only if the given edges can make a valid binary tree.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Recursive stack flow
- •Cycle prevention
- •Post-order reasoning
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply DFS reasoning pattern
💡 Approach
- → A valid binary tree has n-1 edges for n nodes
- → Build adjacency list from edges
- → Use DFS to check for cycles
- → If any node has multiple parents, tree is invalid
- → Time: O(n), Space: O(n)
🛠️ Hints & Pitfalls
Hints
- •A valid binary tree has n-1 edges for n nodes
- •Build adjacency list from edges
- •Use DFS to check for cycles
Common Pitfalls
- •If any node has multiple parents, tree is invalid
- •Time: O(n), Space: O(n)
🧪 Test Cases
Test Case 1
Not run Input:
validTree(5, [[0,1],[0,2],[0,3],[0,4]]); Expected:
false Test Case 2
Not run Input:
validTree(5, [[0,1],[1,2],[2,3],[2,4]]); Expected:
false Test Case 3
Not run Input:
validTree(n: number, edges: number[][]); Expected:
Computed from hidden reference 📝 Code Editor
📤 Output