当前位置:网站首页>leetcode 865. Smallest Subtree with all the Deepest Nodes | 865. The smallest subtree with all the deepest nodes (BFs of the tree, parent reverse index map)

leetcode 865. Smallest Subtree with all the Deepest Nodes | 865. The smallest subtree with all the deepest nodes (BFs of the tree, parent reverse index map)

2022-07-08 02:03:00 Cold spring HQ

subject

https://leetcode.com/problems/smallest-subtree-with-all-the-deepest-nodes/
 Insert picture description here

Answer key

/** * 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) {
    
        //  Sequence traversal , Record the deepest layer 
        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;
        }

        //  Create a tree reverse index table 
        HashMap<TreeNode, TreeNode> parentMap = new HashMap<>();
        dfs(root, parentMap);

        //  Look up from every node in the deepest layer parent, Passing by , Node passing times count++, Find the earliest count==n The ancestors of the 
        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);
        }
    }
}

 Insert picture description here

原网站

版权声明
本文为[Cold spring HQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/189/202207080037095933.html