又一次给评论区的大神跪了。
首先我自己的解法:
class Solution {
public:
TreeNode* lcaDeepestLeaves(TreeNode* root) {
vector<TreeNode*> tempPath, maxDepthPath;
int maxDepth = 0;
helper(root, 0, maxDepth, tempPath, maxDepthPath);
return maxDepthPath.empty()? nullptr : maxDepthPath.back();
}
private:
void helper(TreeNode* node, int depth, int& maxDepth, vector<TreeNode*>& tempPath, vector<TreeNode*>& maxDepthPath) {
if (!node)
return;
++depth;
tempPath.push_back(node);
if (!node->left && !node->right) {
if (depth < maxDepth) {
tempPath.pop_back();
return;
}
if (depth > maxDepth) {
maxDepthPath = tempPath;
maxDepth = depth;
}
if (depth == maxDepth) {
handle(maxDepthPath, tempPath);
}
}
if (node->left)
helper(node->left, depth, maxDepth, tempPath, maxDepthPath);
if (node->right)
helper(node->right, depth, maxDepth, tempPath, maxDepthPath);
tempPath.pop_back();
}
void handle(vector<TreeNode*>& maxDepthPath, vector<TreeNode*>& tempPath) {
if (maxDepthPath.empty()) {
maxDepthPath = tempPath;
return;
}
int i = 0;
for (; i < maxDepthPath.size(); ++i) {
if (maxDepthPath[i] != tempPath[i])
break;
}
for (int j = maxDepthPath.size()-1; j >= i; --j)
maxDepthPath.pop_back();
}
};
又长又臭。
来看看评论区的解法:
class Solution {
public:
TreeNode* lcaDeepestLeaves(TreeNode* root) {
return helper(root).first;
}
private:
pair<TreeNode*, int> helper(TreeNode* node) {
if (!node)
return make_pair(nullptr, 0);
auto lp = helper(node->left);
auto rp = helper(node->right);
if (lp.second > rp.second)
return make_pair(lp.first, lp.second+1);
if (lp.second < rp.second)
return make_pair(rp.first, rp.second+1);
return make_pair(node, lp.second+1);
}
};
简洁优雅。
我能说什么呢(真是个辣鸡