当前位置:网站首页>leetcode 865. Smallest Subtree with all the Deepest Nodes | 865.具有所有最深节点的最小子树(树的BFS,parent反向索引map)

leetcode 865. Smallest Subtree with all the Deepest Nodes | 865.具有所有最深节点的最小子树(树的BFS,parent反向索引map)

2022-07-08 00:37:00 寒泉Hq

题目

https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
在这里插入图片描述

题解

/** * 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 TreeNode subtreeWithAllDeepest(TreeNode root) {
    
        // 层序遍历,记录最深层
        Queue<TreeNode> preQueue = new LinkedList<>();
        Queue<TreeNode> curQueue = new LinkedList<>();
        Queue<TreeNode> nextQueue;
        curQueue.offer(root);
        while (!curQueue.isEmpty()) {
    
            preQueue = new LinkedList<>(curQueue);
            nextQueue = new LinkedList<>();
            while (!curQueue.isEmpty()) {
    
                TreeNode cur = curQueue.poll();
                if (cur.left != null) {
    
                    nextQueue.offer(cur.left);
                }
                if (cur.right != null) {
    
                    nextQueue.offer(cur.right);
                }
            }
            if (nextQueue.isEmpty()) {
    
                break;
            }
            curQueue = nextQueue;
        }

        // 建立树反向索引表
        HashMap<TreeNode, TreeNode> parentMap = new HashMap<>();
        dfs(root, parentMap);

        // 从最深层每个节点向上找parent,路过时,节点经过次数count++,找到最早出现count==n的祖先
        HashMap<Integer, Integer> countMap = new HashMap<>();
        int n = preQueue.size();
        while (!preQueue.isEmpty()) {
    
            TreeNode cur = preQueue.poll();
            while (cur != null) {
    
                int count = countMap.getOrDefault(cur.val, 0) + 1;
                if (count == n) {
    
                    return cur;
                }
                countMap.put(cur.val, count);
                cur = parentMap.get(cur);
            }
        }
        return null;
    }

    public void dfs(TreeNode node, HashMap<TreeNode, TreeNode> map) {
    
        if (node.left != null) {
    
            map.put(node.left, node);
            dfs(node.left, map);
        }
        if (node.right != null) {
    
            map.put(node.right, node);
            dfs(node.right, map);
        }
    }
}

在这里插入图片描述

原网站

版权声明
本文为[寒泉Hq]所创,转载请带上原文链接,感谢
https://hanquan.blog.csdn.net/article/details/125578778