Closest Leaf in a Binary Tree
TreesBFS
MediumLeetCode #742
Problem Statement
Given the `root` of a binary tree and an integer `k`, find the value of the closest leaf node to the node with value `k` in the tree.
Example
Input: root = [1,2,3], k = 1
Output: 2
Algorithm Explanation
This problem can be solved by converting the tree into a graph and then performing a breadth-first search (BFS) starting from the node with value `k`.
Algorithm Steps
- Build Graph: First, we traverse the tree and build an adjacency list representation of the tree as an undirected graph. We also need to find the starting node (the one with value `k`).
- BFS: We start a BFS from the node with value `k`. We use a queue to keep track of the nodes to visit and a set to keep track of visited nodes to avoid cycles.
- Find Closest Leaf: The first leaf node we encounter during the BFS will be the closest one to the starting node. A node is a leaf if it has only one connection in our graph (its parent), and it's not the root of the original tree.
Build Graph
Graph built from tree.
Queue
Visited
Closest Leaf in a Binary Tree Solution