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);
}
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://hanquan.blog.csdn.net/article/details/125578778
内容来源于网络,如有侵权,请联系作者删除!