All Nodes Distance K in Binary Tree
TreesBFS / Graph
MediumLeetCode #863
Problem Statement
Given the root of a binary tree, the value of a target node, and an integer k, return an array of the values of all nodes that have a distance k from the target node.
Example
target = 5, k = 2
Output: [7, 4, 1]
Algorithm Explanation
This problem can be solved by treating the tree as an undirected graph. Once we have a graph representation, we can perform a Breadth-First Search (BFS) starting from the target node to find all nodes at distance K.
Algorithm Steps
- Graph Conversion: Traverse the binary tree (using DFS or BFS) to build an adjacency list that represents the connections between nodes. Each node will have pointers to its parent, left child, and right child.
- BFS from Target: Start a BFS from the `target` node. Use a queue to keep track of nodes to visit and their distance from the target.
- Track Visited Nodes: Use a set to keep track of visited nodes to avoid cycles and redundant processing.
- Find Nodes at Distance K: When the distance of a node in the BFS equals `k`, add its value to the result list.
- Stop Early: If the distance exceeds `k`, we can stop searching down that path.
Graph Construction
Start building graph. Queue: [3]
Adjacency List
All Nodes Distance K Solution