Closest Node to Path in Tree — LeetCode 2277 Python Solution
- Problem
- #2277
- Pattern
- Tree Traversal
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a positive integer n representing the number of nodes in a tree, numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges of length n - 1, where edges[i] = [node1i, node2i] denotes that there is a bidirectional edge connecting node1i and node2i in the tree.
Example
- Input
- n = 7, edges = [[0,1],[0,2],[0,3],[1,4],[2,5],[2,6]], query = [[5,3,4],[5,3,6]]
- Output
- [0,2]
- Explanation
- The path from node 5 to node 3 consists of the nodes 5, 2, 0, and 3.
Complexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 2277. Closest Node to Path in Tree is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2277. Closest Node to Path in Tree?
- LeetCode 2277. Closest Node to Path in Tree is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2277. Closest Node to Path in Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 2277. Closest Node to Path in Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 2277. Closest Node to Path in Tree cover?
- LeetCode 2277. Closest Node to Path in Tree is tagged Tree, Depth-First Search, Breadth-First Search and Array on LeetCode.
- Is LeetCode 2277. Closest Node to Path in Tree a premium problem?
- Yes. LeetCode 2277. Closest Node to Path in Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.