Description
Submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
unordered_set<TreeNode*> nodes;
TreeNode* ret = nullptr;
int heightOfTree(TreeNode* root) {
if(!root) return -1;
return max(heightOfTree(root->left), heightOfTree(root->right)) + 1;
}
void findDeepestLeaves(TreeNode* root, int height) {
if(!root) return;
if(height == 0) nodes.insert(root);
else {
findDeepestLeaves(root->left, height - 1);
findDeepestLeaves(root->right, height - 1);
}
}
int dfs(TreeNode* root) {
if(!root) return 0;
int count = dfs(root->left) + dfs(root->right) + (nodes.find(root) != nodes.end());
if(count == nodes.size() && !ret) {
ret = root;
}
return count;
}
public:
TreeNode* lcaDeepestLeaves(TreeNode* root) {
int height = heightOfTree(root);
findDeepestLeaves(root, height);
dfs(root);
return ret;
}
};