Closest Leaf in a Binary Tree

Input:
root = [1,2,3,4,null,null,null,5,null,6], k = 2
Diagram of binary tree:
             1
            / \
           2   3
          /
         4
        /
       5
      /
     6

Output: 3
Explanation: The leaf node with value 3 (and not the leaf node with value 6) is nearest to the node with value 2.

思路:把tree变换成图,建立图的过程,顺便把startNode找到;然后在图中做BFS,无向图,必须要有visited,否则会有死循环;

/**
 * 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 {
    public int findClosestLeaf(TreeNode root, int k) {
        HashMap<TreeNode, List<TreeNode>> graph = new HashMap<>();
        TreeNode[] targetNode = new TreeNode[1];
        buildGraph(graph, root, null, targetNode, k);
        
        Queue<TreeNode> queue = new LinkedList<>();
        HashSet<TreeNode> visited = new HashSet<>();
        queue.offer(targetNode[0]);
        visited.add(targetNode[0]);
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if(node.left == null && node.right == null) {
                    return node.val;
                }
                for(TreeNode neighbor: graph.get(node)) {
                    if(!visited.contains(neighbor)) {
                        visited.add(neighbor);
                        queue.offer(neighbor);
                    }
                }
            }
        }
        return -1;
    }
    
    private void buildGraph(HashMap<TreeNode, List<TreeNode>> graph,
                           TreeNode root, TreeNode parent, TreeNode[] targetNode, int target) {
        if(root == null) {
            return;
        }
        if(root.val == target) {
            targetNode[0] = root;
        }
        graph.putIfAbsent(root, new ArrayList<TreeNode>());
        if(root.left != null) {
            graph.get(root).add(root.left);
            buildGraph(graph, root.left, root, targetNode, target);
        }
        if(root.right != null) {
            graph.get(root).add(root.right);
            buildGraph(graph, root.right, root, targetNode, target);
        }
        if(parent != null) {
            graph.get(root).add(parent);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值