/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* subtreeWithAllDeepest(TreeNode* root) {
return helper(root, 0).first;
}
private:
pair<TreeNode*, int> helper(TreeNode* root, int depth) {
if (!root) return {NULL, 0};
const auto left = helper(root->left, depth + 1);
const auto right = helper(root->right, depth + 1);
if (left.second > right.second) {
return left;
} else if (right.second > left.second) {
return right;
} else {
return {root, max(left.second, depth)};
}
}
};
public class Result {
TreeNode node;
int depth;
Result(TreeNode node, int depth) {
this.node = node;
this.depth = depth;
}
}
public TreeNode lca(TreeNode node) {
return helper(node).node;
}
public Result helper(TreeNode node) {
if (node == null) {
return new Result(null, 0);
}
int max = 0, count = 0;
TreeNode target = node;
for (TreeNode sub : node.children) {
Result subres = helper(sub);
if (subres.depth > max) {
max = subres.depth;
count = 1;
target = subres.node;
} else if (subres.depth == max) {
count++;
target = root;
}
}
return new Result(target, max + 1);
}