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

x33g5p2x  于2022-07-04 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(240)

题目

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);
        }
    }
}

相关文章