KatInterview

743. Closest Leaf in a Binary Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the value of the leaf node that is closest to a given target node with value k. The "distance" is measured by the number of edges in the path. A path between two nodes in a binary tree can go downwards to children or upwards to ancestors. The standard tree traversal (like DFS or BFS) is inherently directional (from parent to child). To find the shortest path in terms of edges, we need to be able to move in any direction (up, left, right), which suggests treating the tree as a general, unweighted graph.

Solution

Closest Leaf in a Binary Tree in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
import collections

class Solution:
    def findClosestLeaf(self, root: Optional[TreeNode], k: int) -> int:
        # Adjacency list to represent the tree as a graph
        graph = collections.defaultdict(list)
        start_node = None

        # Use DFS to build the graph and find the starting node for BFS
        def build_graph(node, parent):
            nonlocal start_node
            if not node:
                return
            
            # Find the starting node for BFS
            if node.val == k:
                start_node = node
            
            # Add edges for the undirected graph
            if parent:
                graph[node].append(parent)
                graph[parent].append(node)
            
            build_graph(node.left, node)
            build_graph(node.right, node)

        # 1. Build the graph and find the start node
        build_graph(root, None)
        
        # 2. Perform BFS from the start node
        queue = collections.deque([start_node])
        visited = {start_node}
        
        while queue:
            curr_node = queue.popleft()
            
            # If the current node is a leaf, it's the closest one due to BFS property
            if not curr_node.left and not curr_node.right:
                return curr_node.val
            
            # Add all unvisited neighbors to the queue
            for neighbor in graph[curr_node]:
                if neighbor not in visited:
                    visited.add(neighbor)
                    queue.append(neighbor)
        
        return -1 # Should not be reached based on problem constraints

Closest Leaf in a Binary Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // Map to store graph representation, and reference to the start node
    private Map<TreeNode, List<TreeNode>> graph;
    private TreeNode startNode;
    private int targetK;

    public int findClosestLeaf(TreeNode root, int k) {
        graph = new HashMap<>();
        targetK = k;
        startNode = null;

        // 1. Convert tree to an undirected graph and find the target node
        buildGraph(root, null);

        // 2. Perform BFS from the target node to find the nearest leaf
        Queue<TreeNode> queue = new LinkedList<>();
        Set<TreeNode> visited = new HashSet<>();

        queue.add(startNode);
        visited.add(startNode);

        while (!queue.isEmpty()) {
            TreeNode curr = queue.poll();

            // If the current node is a leaf, it's the closest one due to BFS property.
            if (curr.left == null && curr.right == null) {
                return curr.val;
            }

            // Add all unvisited neighbors to the queue for the next level of search.
            if (graph.containsKey(curr)) {
                for (TreeNode neighbor : graph.get(curr)) {
                    if (!visited.contains(neighbor)) {
                        visited.add(neighbor);
                        queue.add(neighbor);
                    }
                }
            }
        }

        return -1; // Should not be reached given problem constraints
    }

    // Helper function to build the graph using DFS
    private void buildGraph(TreeNode node, TreeNode parent) {
        if (node == null) {
            return;
        }

        // Identify the start node for our BFS
        if (node.val == targetK) {
            startNode = node;
        }

        // Create edges for the undirected graph
        if (parent != null) {
            graph.computeIfAbsent(node, x -> new ArrayList<>()).add(parent);
            graph.computeIfAbsent(parent, x -> new ArrayList<>()).add(node);
        }

        // Recurse for children
        buildGraph(node.left, node);
        buildGraph(node.right, node);
    }
}

Closest Leaf in a Binary Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int findClosestLeaf(TreeNode* root, int k) {
        // Adjacency list to represent the tree as a graph
        std::unordered_map<TreeNode*, std::vector<TreeNode*>> graph;
        TreeNode* startNode = nullptr;
        
        // Use a lambda for recursive DFS to build the graph
        std::function<void(TreeNode*, TreeNode*)> buildGraph = 
            [&](TreeNode* node, TreeNode* parent) {
            if (!node) {
                return;
            }
            // Find the starting node for BFS
            if (node->val == k) {
                startNode = node;
            }
            // Add edges for the undirected graph
            if (parent) {
                graph[node].push_back(parent);
                graph[parent].push_back(node);
            }
            // Recurse for children
            buildGraph(node->left, node);
            buildGraph(node->right, node);
        };
        
        // 1. Build the graph and find the start node
        buildGraph(root, nullptr);
        
        // 2. Perform BFS from the start node
        std::queue<TreeNode*> q;
        q.push(startNode);
        std::unordered_set<TreeNode*> visited;
        visited.insert(startNode);
        
        while (!q.empty()) {
            TreeNode* curr = q.front();
            q.pop();
            
            // If the current node is a leaf, it's the closest one found so far
            if (!curr->left && !curr->right) {
                return curr->val;
            }
            
            // Add all unvisited neighbors to the queue
            for (TreeNode* neighbor : graph[curr]) {
                if (visited.find(neighbor) == visited.end()) {
                    visited.insert(neighbor);
                    q.push(neighbor);
                }
            }
        }
        
        return -1; // Should not be reached based on problem constraints
    }
};

Closest Leaf in a Binary Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function findClosestLeaf(root: TreeNode | null, k: number): number {
    if (!root) {
        return -1; // Should not happen given constraints
    }

    const graph: Map<TreeNode, TreeNode[]> = new Map();
    let startNode: TreeNode | null = null;

    // Helper function to build the graph using DFS
    function buildGraph(node: TreeNode | null, parent: TreeNode | null) {
        if (!node) {
            return;
        }

        // Find the start node for BFS
        if (node.val === k) {
            startNode = node;
        }

        // Add edges for the undirected graph
        if (parent) {
            if (!graph.has(node)) graph.set(node, []);
            if (!graph.has(parent)) graph.set(parent, []);
            graph.get(node)!.push(parent);
            graph.get(parent)!.push(node);
        }

        buildGraph(node.left, node);
        buildGraph(node.right, node);
    }

    // 1. Build the graph and find the start node
    buildGraph(root, null);

    if (!startNode) {
        return -1; // k not found, though problem guarantees it exists.
    }

    // 2. Perform BFS from the start node
    const queue: TreeNode[] = [startNode];
    const visited: Set<TreeNode> = new Set([startNode]);

    while (queue.length > 0) {
        const currNode = queue.shift()!; 

        // If the current node is a leaf, it's the closest one due to BFS property
        if (!currNode.left && !currNode.right) {
            return currNode.val;
        }

        // Add all unvisited neighbors to the queue
        const neighbors = graph.get(currNode) || [];
        for (const neighbor of neighbors) {
            if (!visited.has(neighbor)) {
                visited.add(neighbor);
                queue.push(neighbor);
            }
        }
    }

    return -1; // Should not be reached
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.