Problem solution · Python

Closest Leaf in a Binary Tree

Closest Leaf in a Binary Tree: a Python solution using sliding window or two pointers. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Sliding window or two pointers
Source
Kamyu LeetCode Solutions
Length
45 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Sliding window or two pointers

For Closest Leaf in a Binary Tree, the implementation maintains a moving interval and updates only the information that enters or leaves the window.

  1. Choose the invariant that makes a window valid or useful.
  2. Advance the right boundary and add the new element.
  3. Move the left boundary only as needed while maintaining the invariant and updating the answer.

Code notes

  • 45 lines of Python from the credited upstream file closest-leaf-in-a-binary-tree.py.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • No explicit loop blocks detected.

Complexity

Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeClosest Leaf in a Binary Tree · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(n)# Space: O(n) import collections  class Solution(object):    def findClosestLeaf(self, root, k):        """        :type root: TreeNode        :type k: int        :rtype: int        """        def traverse(node, neighbors, leaves):            if not node:                return            if not node.left and not node.right:                leaves.add(node.val)                return            if node.left:                neighbors[node.val].append(node.left.val)                neighbors[node.left.val].append(node.val)                traverse(node.left, neighbors, leaves)            if node.right:                neighbors[node.val].append(node.right.val)                neighbors[node.right.val].append(node.val)                traverse(node.right, neighbors, leaves)         neighbors, leaves = collections.defaultdict(list), set()        traverse(root, neighbors, leaves)        q, lookup = [k], set([k])        while q:            next_q = []            for u in q:                if u in leaves:                    return u                for v in neighbors[u]:                    if v in lookup:                        continue                    lookup.add(v)                    next_q.append(v)            q = next_q        return 0  

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗