AlgoMaster Logo

All Nodes Distance K in Binary Tree

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Convert Tree to Undirected Graph

Intuition:

The problem can be simplified by viewing the binary tree as an undirected graph. Each node can be connected to its children and, for our purposes, we can connect each child back to its parent, forming a graph-like adjacency list. Once this graph is prepared, we can perform a Breadth-First Search (BFS) to find all nodes that are exactly K distance away from the target node.

Steps:

  1. Build Graph: Start by performing a DFS traversal on the tree to convert it into an undirected graph, represented by an adjacency list.
  2. BFS Traversal: Perform a BFS starting from the target node, keeping track of visited nodes to avoid cycles. Record nodes that are exactly K edges away.

Code:

2. DFS to Find Target Node and Explore Neighbors Using BFS

Intuition:

Instead of explicitly building a graph, we can use a combination of DFS and BFS directly on the tree structure. First, use DFS to find the path to the target node. Then, treat this path as the base and perform BFS from the target while marking distances in the BFS.

Steps:

  1. DFS to Target: Find the target node and the path leading to it by using DFS. Mark each node's distance from the root (or considered starting point).
  2. BFS Exploration: Use BFS from the target to find nodes at distance K. Treat any node along the path to the target as an "intermediary root" to account for upward paths.

Code: