Problem solution · Python

Pythagorean Distance Nodes in a Tree

Pythagorean Distance Nodes in a Tree: a Python solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Breadth-first search
Source
Kamyu LeetCode Solutions
Length
38 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Breadth-first search

For Pythagorean Distance Nodes in a Tree, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. Expand each state once, recording distance or reachability for unseen neighbours.

Code notes

  • 38 lines of Python from the credited upstream file pythagorean-distance-nodes-in-a-tree.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

Complexity

Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codePythagorean Distance Nodes in a Tree · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n)# Space: O(n) # bfsclass Solution(object):    def specialNodes(self, n, edges, x, y, z):        """        :type n: int        :type edges: List[List[int]]        :type x: int        :type y: int        :type z: int        :rtype: int        """        def bfs(x):            dist = [-1]*n            dist[x] = 0            q = [x]            while q:                new_q = []                for u in q:                    for v in adj[u]:                        if dist[v] != -1:                            continue                        dist[v] = dist[u]+1                        new_q.append(v)                q = new_q            return dist         adj = [[] for _ in xrange(n)]        for u, v in edges:            adj[u].append(v)            adj[v].append(u)        dist1 = bfs(x)        dist2 = bfs(y)        dist3 = bfs(z)        return sum(dist1[u]**2+dist2[u]**2+dist3[u]**2 == 2*max(dist1[u], dist2[u], dist3[u])**2 for u in xrange(n)) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗