↓Skip to main content
  1. LeetCode/

LeetCode 3820: Pythagorean Distance Nodes in a Tree

·2 mins· ·
LeetCode Medium Tree Bfs Graph
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2026-01-25

  • Submissions: Accepted (first try)

Approach
#

Every node needs its distances to x, y, and z. Instead of one BFS per node, run one BFS from each of the three targets; each run gives every node’s distance to that target.

A tree has exactly one path between two nodes, so the BFS step count is the distance.

Finally, for each node, sort the three distances and check a² + b² == c².

My Solution
#

from collections import deque

class Solution:
    def specialNodes(self, n: int, edges: List[List[int]], x: int, y: int, z: int) -> int:
        graph = [[] for _ in range(n)]
        for u, v in edges:
            graph[u].append(v)
            graph[v].append(u)

        def bfs(start):
            dist = [-1] * n
            dist[start] = 0
            q = deque([start])
            while q:
                u = q.popleft()
                for v in graph[u]:
                    if dist[v] == -1:
                        dist[v] = dist[u] + 1
                        q.append(v)
            return dist

        dx, dy, dz = bfs(x), bfs(y), bfs(z)

        count = 0
        for i in range(n):
            a, b, c = sorted((dx[i], dy[i], dz[i]))
            if a * a + b * b == c * c:
                count += 1
        return count

Complexity
#

Time O(n): three BFS runs plus one scan. Space O(n).

Mistakes to Avoid
#

  • Running BFS from every node, which is O(n^2).
  • Adding edges in one direction only: tree edges are undirected.
  • Forgetting to sort: c in the Pythagorean check must be the largest.

Interview Explanation
#

I need each node’s distance to three targets, so I flip it around and run one BFS from each target, getting three distance arrays. Paths in a tree are unique, so BFS steps equal distances. For each node I sort its three distances and check whether the squares of the two smaller ones add up to the square of the largest. Three BFS runs, so time is O(n).

Related

LeetCode 1306: Jump Game III
·2 mins
LeetCode Medium Bfs Dfs Graph Array
LeetCode 1306 note: indices are nodes and the two jumps are edges; BFS or DFS decides whether a zero is reachable
LeetCode 865: Smallest Subtree with all the Deepest Nodes
·2 mins
LeetCode Medium Tree Binary-Tree Bfs Dfs Lca
LeetCode 865 note: BFS to the last level and climb together, or one DFS returning (depth, node)
LeetCode 1161: Maximum Level Sum of a Binary Tree
·2 mins
LeetCode Medium Tree Binary-Tree Bfs
LeetCode 1161 note: pushing None into the next level creates a fake level with sum 0
LeetCode 3619: Count Islands With Total Value Divisible by K
·2 mins
LeetCode Medium Dfs Bfs Matrix Graph
LeetCode 3619 note: flood fill each island and sum its values; with up to 10^5 cells, iterate to avoid deep recursion
LeetCode 958: Check Completeness of a Binary Tree
·2 mins
LeetCode Medium Tree Binary-Tree Bfs
LeetCode 958 note: completeness is a global property, so check with BFS whether any node follows the first gap
LeetCode 1339: Maximum Product of Splitted Binary Tree
·2 mins
LeetCode Medium Tree Binary-Tree Dfs
LeetCode 1339 note: compute the total, enumerate every subtree sum, and leave the input untouched