LCA of the Deepest Nodes
Thoughts
Code
/**
* 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)};
}
}
};Last updated