Closest Leaf in a Binary Tree — LeetCode 742 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#742
Reading time
5 min

The problem

Given the root of a binary tree where every node has a unique value and a target integer k, return the value of the nearest leaf node to the target k in the tree. Nearest to a leaf means the least number of edges traveled on the binary tree to reach any leaf of the tree.

Example

Input
root = [1,3,2], k = 1
Output
2
Explanation
Either 2 or 3 is the nearest leaf node to the target of 1.

Python solution

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
class Solution:
    def findClosestLeaf(self, root: Optional[TreeNode], k: int) -> int:
        def dfs(root: Optional[TreeNode], fa: Optional[TreeNode]):
            if root:
                g[root].append(fa)
                g[fa].append(root)
                dfs(root.left, root)
                dfs(root.right, root)

        g = defaultdict(list)
        dfs(root, None)
        q = deque(node for node in g if node and node.val == k)
        vis = set(q)
        while 1:
            node = q.popleft()
            if node:
                if node.left == node.right:
                    return node.val
                for nxt in g[node]:
                    if nxt not in vis:
                        vis.add(nxt)
                        q.append(nxt)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 742. Closest Leaf in a Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 742. Closest Leaf in a Binary Tree?
LeetCode 742. Closest Leaf in a Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 742. Closest Leaf in a Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 742. Closest Leaf in a Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 742. Closest Leaf in a Binary Tree cover?
LeetCode 742. Closest Leaf in a Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.
Is LeetCode 742. Closest Leaf in a Binary Tree a premium problem?
Yes. LeetCode 742. Closest Leaf in a Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview