Closest Leaf Node

user profile image
System made a post.

Given a binary tree, find the closest LEAF node to the target.

public TreeNode closestLeaf(TreeNode root, TreeNode target) {
        if(root == null || target == null) {
            return null;
        Map> mapping = new HashMap();
        buildAdjList(mapping, root, null);

        Queue queue = new LinkedList();
        Set visited = new HashSet();

        for (TreeNode node: mapping.keySet()) {
            if (node != null && node == target) {

        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node != null) {
                if (mapping.get(node).size() <= 1) {
                    return node;
                for (TreeNode n: mapping.get(node)) {
                    if (!visited.contains(n)) {
        return null;

    public void buildAdjList(Map> mapping, TreeNode node, TreeNode p) {
        if (!mapping.containsKey(node)) {
            mapping.put(node, new ArrayList<>());
        if (!mapping.containsKey(p)) {
            mapping.put(p, new ArrayList<>());
        if (node != null) {
            if (node.left != null) {
                buildAdjList(mapping, node.left, node);
            if (node.right != null) {
                buildAdjList(mapping, node.right, node);

One-on-One Algorithm and Coding Training

One-on-One System Design Training

One-on-One Mock Interview

Get one-to-one training from Google Facebook engineers

Top-notch Professionals

Learn from Facebook, Google, Uber senior engineers interviewed 100+
Most recent interview questions and system design topics gathered from aonecode alumnus.
One-to-one online classes. Get feedbacks from real interviewers.

Customized Private Class

Already a coding expert? - Advance straight to hard interview topics of your interest.
New to the ground? - Develop basic coding skills with your own designated mentor.
Days before interview? - Focus on most important problems in target company question bank.

Free Consultation