题目描述
Given a binary tree rooted at root, the depth of each node is the shortest distance to the root.
A node is deepest if it has the largest depth possible among any node in the entire tree.
The subtree of a node is that node, plus the set of all descendants of that node.
Return the node with the largest depth such that it contains all the deepest nodes in its subtree.


方法思路
错误的思路:
只考虑了示例中的情况,没想周全

class Solution {
Map<TreeNode, TreeNode> parent_children;// = new HashMap<>()
Map<TreeNode, Integer> node_depth;// = new HashMap<>()
int max_depth;// = 0
public TreeNode subtreeWithAllDeepest(TreeNode root) {
parent_children = new HashMap<TreeNode, TreeNode>();
node_depth = new HashMap<TreeNode, Integer>();
max_depth = 0;
dfs(root, null, 0);
TreeNode node = root;
int count = 0;
for(TreeNode temp : node_depth.keySet()){
if(node_depth.get(temp) == max_depth){
node = temp;
count++;
}
}
return count == 2 ? parent_children.get(node) : node;
}
public void dfs(TreeNode child, TreeNode parent, int depth){
if(child == null) return;
max_depth = (max_depth > depth) ? max_depth : depth;
node_depth.put(child, depth);
if(parent == null){
parent_children.put(child, child);
}else{
parent_children.put(child, parent);
}
dfs(child.left, child, depth + 1);
dfs(child.right, child, depth + 1);
}
}
Approach 1: Paint Deepest Nodes

class Solution {
Map<TreeNode, Integer> depth;
int max_depth;
public TreeNode subtreeWithAllDeepest(TreeNode root) {
depth = new HashMap();
depth.put(null, -1);
dfs(root, null);
max_depth = -1;
for (Integer d: depth.values())
max_depth = Math.max(max_depth, d);
return answer(root);
}
public void dfs(TreeNode node, TreeNode parent) {
if (node != null) {
depth.put(node, depth.get(parent) + 1);
dfs(node.left, node);
dfs(node.right, node);
}
}
public TreeNode answer(TreeNode node) {
if (node == null || depth.get(node) == max_depth)
return node;
TreeNode L = answer(node.left),
R = answer(node.right);
if (L != null && R != null) return node;
if (L != null) return L;
if (R != null) return R;
return null;
}
}
Approach 2: Recursion
class Solution {
public TreeNode subtreeWithAllDeepest(TreeNode root) {
return dfs(root).node;
}
// Return the result of the subtree at this node.
public Result dfs(TreeNode node) {
if (node == null) return new Result(null, 0);
Result L = dfs(node.left),
R = dfs(node.right);
if (L.dist > R.dist) return new Result(L.node, L.dist + 1);
if (L.dist < R.dist) return new Result(R.node, R.dist + 1);
return new Result(node, L.dist + 1);
}
}
/**
* The result of a subtree is:
* Result.node: the largest depth node that is equal to or
* an ancestor of all the deepest nodes of this subtree.
* Result.dist: the number of nodes in the path from the root
* of this subtree, to the deepest node in this subtree.
*/
class Result {
TreeNode node;
int dist;
Result(TreeNode n, int d) {
node = n;
dist = d;
}
}

本文探讨了寻找二叉树中包含所有最深层节点的子树问题。通过两种方法——标记最深层节点并回溯以及递归策略,实现了高效的算法设计。文章深入解析了不同方法的实现细节和技术要点。
587

被折叠的 条评论
为什么被折叠?



